mouseMoveEvent中判断鼠标状态

函数区别(官方解析)
button返回产生事件的按钮
buttons返回产生事件的按钮状态,函数返回当前按下的所有按钮,按钮状态可以是Qt::LeftButton,Qt::RightButton,Qt::MidButton或运算组合

假设鼠标左键已经按下:
如果移动鼠标,会发生move事件,button返回Qt::NoButton,buttons返回LeftButton;
再按下右键,会发生press事件,button返回RightButton,buttons返回LeftButton | RightButton;
再移动鼠标,会发生move事件,button返回Qt::NoButton,buttons返回LeftButton | RightButton;
再松开左键,会发生Release事件,button返回LeftButton,buttons返回RightButton。
也就是说,button返回“发生此事件的那个按钮”,buttons返回"发生此事件时处于按下状态的那些按钮"。

常用按钮值

按钮
NoButton0x00000000
LeftButton0x00000001
RightButton0x00000002
MidButton0x00000004 // ### Qt 6: remove me
MiddleButtonMidButton
被按下按钮返回值
左键1
右键2
中键4
左 + 右3
左 + 中5
右 + 中6
左 + 中 + 右7

实例代码

判断方法结果
event->button() == Qt::LeftButton && (event->buttons() & Qt::LeftButton)左键按下
event->buttons() & Qt::LeftButton左键处于一直按下
event->button() != Qt::LeftButton && (event->buttons() & Qt::LeftButton)左键处于一直按下(此事件不是由左键发生)
event->button() == Qt::LeftButton && (!(event->buttons() & Qt::LeftButton))左键释放
event->button() == Qt::RightButton && (event->buttons() & Qt::RightButton)右键按下
event->buttons() & Qt::RightButton右键处于一直按下
event->button() != Qt::RightButton && (event->buttons() & Qt::RightButton)右键处于一直按下(此事件不是由右键发生)
event->button() == Qt::RightButton && (!(event->buttons() & Qt::RightButton))右键释放
void MyWidget::mousePressEvent(QMouseEvent *event)
{
	processMouseEvent(event);
}

void MyWidget::mouseReleaseEvent(QMouseEvent *event)
{
	processMouseEvent(event);
}

void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
	processMouseEvent(event);
}

void MyWidget::processMouseEvent(QMouseEvent * event)
{
	if (event->button() == Qt::LeftButton && (event->buttons() & Qt::LeftButton))
	{
		// 左键按下
	}

	if (event->button() != Qt::LeftButton && (event->buttons() & Qt::LeftButton))
	{
		// 左键处于一直按下
	}

	if (event->button() == Qt::LeftButton && (!(event->buttons() & Qt::LeftButton)))
	{
		// 左键释放
	}

	if (event->button() == Qt::RightButton && (event->buttons() & Qt::RightButton))
	{
		// 右键按下
	}

	if (event->button() != Qt::RightButton && (event->buttons() & Qt::RightButton))
	{
		// 右键处于一直按下
	}

	if (event->button() == Qt::RightButton && (!(event->buttons() & Qt::RightButton)))
	{
		// 右键释放
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值