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);
}
相关推荐
△曉風殘月〆1 小时前
如何在Linux中安装Qt开发环境
linux·运维·qt
Quz6 小时前
QML 选择控件:Switch、CheckBox 与 RadioButton
qt
熬夜苦读学习7 小时前
Qt常用控件
服务器·开发语言·qt
夏玉林的学习之路8 小时前
Qt 项目编译错误排查与解决记录
开发语言·qt
Quz1 天前
QML 基础按钮:Button、RoundButton 与 DelayButton
qt
Quz1 天前
QML ToolTip 组件:图标、多行文本与阴影
qt
xcyxiner1 天前
DicomViewer14(读取图像按固定窗宽窗位显示)
qt
马里马里奥-2 天前
从零搭建AI Agent工具链的技术文章大纲
开发语言·qt
Quz2 天前
QML 与 JavaScript 交互方式:内联函数、外部文件、信号槽与工作线程
javascript·qt
Quz2 天前
QML ToolTip 组件:延迟提示与自定义外观
qt