2

I am trying to capture the mouse release event in a widget ensuring that the mouse was previously pressed in same widget. mouseReleaseEvent is successfully called but I don't know what to do with the parameter QMouseEvent to check if the position of the mouse is inside the widget. My current code:

void DeviceWidget::mouseReleaseEvent(QMouseEvent* e)
{
    if (_mouseClick)
    {
        _mouseClick = false;
        emit mouseClick(_deviceInformation);
    }
}

Thank you so much,

Didac Perez Parera
  • 3,734
  • 3
  • 52
  • 87
  • This event should only be triggered if the mouse was on the widget when it was released. Checking for it is superfluous. – RedX Sep 30 '13 at 15:13
  • Not, it's triggered even if I release the mouse in another place such as the desktop. – Didac Perez Parera Sep 30 '13 at 15:17
  • Take a look at [Qt - Determine absolute widget and cursor position](http://stackoverflow.com/questions/4450595/qt-determine-absolute-widget-and-cursor-position) – RedX Sep 30 '13 at 15:21
  • The release event is reported to the same widget that had the press event. You should do nothing special about it. The actual pointer position at the time of release is irrelevant. – n. m. could be an AI Sep 30 '13 at 15:27

1 Answers1

6

You need to check if the local position of the mouse release event is within your widget. I don't think there's a reason to use the _mouseClick member variable. This method will only be called if the mouse press was on this widget. When you press the button, the widget starts tracking the mouse, and it will receive the release event - no matter where the mouse was released.

void DeviceWidget::mouseReleaseEvent(QMouseEvent* e)
{
    if (rect().contains(e->localPos()->toPoint()) {
        emit mouseClick(_deviceInformation);
    }
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313