Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the released button inside MouseReleaseEvent in Qt

In MouseReleaseEvent(QMouseEvent *e), is there a way to know which button was released without using a new variable ? I mean something like in the MousePressEvent(QMouseEvent *e) with e.buttons(). I tried e.buttons() in the releaseEvent it's not working (which is logical).

like image 775
Othman Benchekroun Avatar asked Aug 21 '14 12:08

Othman Benchekroun


2 Answers

e is 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
  }
}

A switch statement also works. I prefer the series of if -- else if because they make it easier to handle evente modifiers, i.e., e->modifiers() in order to check for alt or control clicks. The series of if's is short enough not to create any burden on the program.

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

like image 116
rpsml Avatar answered Oct 12 '22 18:10

rpsml


The problem in the posted code is this: -

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

As the Qt documentation states for the release event: -

... For mouse release events this excludes the button that caused the event.

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

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

Returns the button that caused the event.

So you can use the button() function here.

like image 33
TheDarkKnight Avatar answered Oct 12 '22 16:10

TheDarkKnight