How to get the released button inside MouseReleaseEvent in Qt

In MouseReleaseEvent(QMouseEvent *e) , is there a way to find out which button was released without using a new variable? I mean something like MousePressEvent(QMouseEvent *e) with e.buttons() . I tried e.buttons() in release so that it doesn't work (which is logical).

+5
source share
2 answers

e already a variable. Just use:

 void mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) // Left button... { // Do something related to the left button } else if (e->button() == Qt::RightButton) // Right button... { // Do something related to the right button } else if (e->button() == Qt::MidButton) // Middle button... { // Do something related to the middle button } } 
Operator

A switch also works. I prefer the if -- else if series because they simplify the handling of evente modifiers, i.e. e->modifiers() to check alt or control clicks. The if series is short enough not to create any load on the program.

EDIT: note that you should use the button() function, not its plural version of buttons() . See explanation in @ Merlin069's answer.

+8
source

The problem in the hosted code is this: -

 if(e->buttons() & Qt::LeftButton) 

As reported by Qt documentation for the release event: -

... For mouse release events, this excludes the button that triggered the event.

The buttons () function will return the current state of the buttons, since this is a release event, the code will return false since it is no longer pressed.

However, the documentation for the button () function indicates: -

Returns the button that raised the event.

So you can use function () here.

+7
source

Source: https://habr.com/ru/post/1200834/


All Articles