Qt鼠标按钮

Qt Mouse Buttons

本文关键字:按钮 鼠标 Qt      更新时间:2023-10-16

我正在使用Qt一段时间,有一些事情我正在做的工作,但我不明白为什么,像这样:

(event->buttons() & Qt::MiddleButton)

这将返回true时,按下MiddleButton,但我的问题是语法,Qt说Qt::MiddleButton的值为4,所以作为一个布尔值将始终返回真,所以这意味着表达式等于这个:(event->buttons())…这也不合逻辑……有人能解释一下吗?

From Qt docs

Qt::LeftButton      0x00000001 ---> 00000001b
Qt::RightButton     0x00000002 ---> 00000010b
Qt::MiddleButton    0x00000004 ---> 00000100b

最右边的列是二进制表示!

Left+Right  --> buttons(): 3
Left+Middle --> buttons(): 5
.......

然后(buttons() & Qt::MiddleButton)测试与MiddleButton相关的位是否设置

Left+Right  --> 00000011 --> 00000011 & 00000100 = 00000000 --> FALSE 
Left+Middle --> 00000011 --> 00000101 & 00000100 = 00000100 --> TRUE 

问题是您将逻辑运算符&&与位运算符和&运算符混合在一起。它们不一样。例如

100 && 010 = True  (both numbers are not 0)
100 &  010 = False (gives 0)

检查仅bool(event->buttons() == 0)将给你true,如果没有按钮按下和false,如果任何按钮按下。要检查特定的按钮,需要使用按位'&'操作符。