Reputation: 2018
I'm using Qt for a while, there is some things i'm doing that are working, but I don't understand why, like this one :
(event->buttons() & Qt::MiddleButton)
this would return true
when the MiddleButton is pressed, but my problem is the syntax, Qt says that Qt::MiddleButton has a value of 4 so as a boolean is would always return true, so that means that the expression is equivalent to this : (event->buttons())
... And that's not logical neither ... Can someone please explain ??
Upvotes: 0
Views: 2480
Reputation: 21220
The problem is that you mix logical operator &&
with bitwise AND &
operator. They are not the same. For example
100 && 010 = True (both numbers are not 0)
100 & 010 = False (gives 0)
Checking for only bool(event->buttons() == 0)
will give you true
if there is no button pressed and false
if any button is pressed. To check for a particular button, you need to use bitwise '&' operator.
Upvotes: 1
Reputation: 1860
From Qt docs
Qt::LeftButton 0x00000001 ---> 00000001b
Qt::RightButton 0x00000002 ---> 00000010b
Qt::MiddleButton 0x00000004 ---> 00000100b
The rightmost column is a binary representation! So,
Left+Right --> buttons(): 3
Left+Middle --> buttons(): 5
.......
Then (buttons() & Qt::MiddleButton)
test if the bit related to MiddleButton is set
Left+Right --> 00000011 --> 00000011 & 00000100 = 00000000 --> FALSE
Left+Middle --> 00000011 --> 00000101 & 00000100 = 00000100 --> TRUE
Upvotes: 1