Qt事件——鼠标事件

通过label来显示各种事件

鼠标按下事件

cpp 复制代码
//按下显示坐标
void MyLabel::mousePressEvent(QMouseEvent * ev)
{
	int i = ev->x();
	int j = ev->y();

	//判断按下的鼠标键位
	if (ev->button() == Qt::LeftButton) {
		qDebug() << "LeftButton";
	}
	else if (ev->button() == Qt::RightButton) {
		qDebug() << "RightButton";
	}
	else if (ev->button() == Qt::MidButton)
	{
		qDebug() << "MidButton";
	}

	QString text = QString("<center><h1>Mouse Press:(%1,%2)</center></h1>").arg(i).arg(j);
	this->setText(text);
}


鼠标抬起事件

cpp 复制代码
//鼠标抬起
void MyLabel::mouseReleaseEvent(QMouseEvent* ev)
{
	QString text = QString("<center><h1>Mouse Release:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());
	this->setText(text);
}

鼠标移动事件

cpp 复制代码
//鼠标移动,不设置this->setMouseTracking(true);需要按下后移动才有效
void MyLabel::mouseMoveEvent(QMouseEvent* ev)
{
	QString text = QString("<center><h1>Mouse Move:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());
	this->setText(text);
}
cpp 复制代码
#include "MyLabel.h"
#include <QMouseEvent>
#include <QDebug>

MyLabel::MyLabel(QWidget *parent)
	: QLabel(parent)
{
	//设置默认追踪鼠标,就可以不先点击就触发移动事件
	this->setMouseTracking(true);
}

MyLabel::~MyLabel()
{}

//按下显示坐标
void MyLabel::mousePressEvent(QMouseEvent * ev)
{
	int i = ev->x();
	int j = ev->y();

	//判断按下的鼠标键位
	if (ev->button() == Qt::LeftButton) {
		qDebug() << "LeftButton";
	}
	else if (ev->button() == Qt::RightButton) {
		qDebug() << "RightButton";
	}
	else if (ev->button() == Qt::MidButton)
	{
		qDebug() << "MidButton";
	}

	QString text = QString("<center><h1>Mouse Press:(%1,%2)</center></h1>").arg(i).arg(j);
	this->setText(text);
}

//鼠标抬起
void MyLabel::mouseReleaseEvent(QMouseEvent* ev)
{
	QString text = QString("<center><h1>Mouse Release:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());
	this->setText(text);
}

//鼠标移动,不设置this->setMouseTracking(true);需要按下后移动才有效
void MyLabel::mouseMoveEvent(QMouseEvent* ev)
{
	QString text = QString("<center><h1>Mouse Move:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());
	this->setText(text);
}
相关推荐
bkspiderx6 小时前
Qt 的消息机制:事件驱动与信号槽的底层逻辑
开发语言·qt·信号槽·事件驱动·qt 的消息机制
江湖人称菠萝包7 小时前
【Qt】《Qt 5.9 C++开发指南》笔记-Chapter11-数据库
笔记·qt·qt5
励志不掉头发的内向程序员8 小时前
【从零写一个CAD 02】画完第一条线之后:实体容器、Esc 取消,和按了没反应的键盘
开发语言·c++·qt·学习·系统架构
Quz13 小时前
QML TreeView:排序与搜索过滤
qt
Quz13 小时前
QML TreeView:基础树视图与自定义委托
qt
Junfeng的技术笔记19 小时前
基于 C++/Qt 的雷达回波信号检测与测距仿真系统
qt
Quz20 小时前
QML TableView:自定义样式与排序表格
qt
Quz20 小时前
QML TableView:可编辑表格与 SQLite 数据持久化
qt·sqlite
Quz20 小时前
QML ListView:C++ 数据模型与 ProxyModel 实时过滤
qt
Quz20 小时前
QML ListView 入门:自定义样式与数据交互
qt