Search code examples
c++qtqmouseevent

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


Solution

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