Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was reading some tutorial about openGL in qt. One of the mouse event slot has this code in it:

if (event->buttons() & Qt::LeftButton) {    
    rotationX += 180 * dy;
    rotationY += 180 * dx;
    updateGL();
}

what does the & operator do in the if statement? is it exactly the same as == ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is not the same as ==. It is bitwise AND operator. What the expression does is that it takes the return value from event->buttons() and bitwise AND's it with the value represented by Qt::LeftButton. If the resulting value is non-zero the block is being executed.

In essence, it checks if the button specified by Qt::LeftButton is held down.

The reason why the bitwise AND operator is used here is something called a bitmask. What it means is that the return value of event->buttons() is just a value which has it's bits represent different kinds of states. What is done with the &-operator here is that it checks if certain bits(denoted by Qt::LeftButton) are being set(1) or unset(0) in the value returned by event->buttons(). The return value is zero if no tested bit is set, and non-zero, if at least one of the tested bits is set.

More details of how bitwise operations work can be found here: Wikipedia article about Bitwise operations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...