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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With