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)))
	{
		// 右键释放
	}