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返回"發生此事件時處於按下狀態的那些按鈕"。

常用按鈕值

按鈕
NoButton 0x00000000
LeftButton 0x00000001
RightButton 0x00000002
MidButton 0x00000004 // ### Qt 6: remove me
MiddleButton MidButton
被按下按鈕 返回值
左鍵 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)))
	{
		// 右鍵釋放
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章