8

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).

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36

2 Answers2

14

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.

rpsml
  • 1,486
  • 14
  • 21
  • you don't understand, I thank you though for the answer. I already know that e is a variable, that's why i said "new variable". This code works when it's the `MousePressEvent` because there is a button pressed, but on release there is no button pressed so e->button() doesn't have a value. – Othman Benchekroun Aug 21 '14 at 12:36
  • 2
    The above code works. I use it in all my mouse button handling. The value of e is the button which was just released... Note that I am using button(), not buttons()... – rpsml Aug 21 '14 at 12:37
  • Worth noting: it may get tricky with left-handed mouse. Left button may become right – prajmus Aug 21 '14 at 12:40
  • Sorry, my bad, the debug mode doesn't enter the `if` bloc because it contains only a declaration of a variable, It looked like it wasn't getting on it. – Othman Benchekroun Aug 21 '14 at 12:51
  • @user3883676 I don't know what to say. I just tested and it works fine. There is a `{` missing just after the `if` bloc in your posted code. – rpsml Aug 21 '14 at 12:52
  • @rpsml My bad, look at the precedent comment – Othman Benchekroun Aug 21 '14 at 12:54
11

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.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85