Detect if the mouse is clicked outside GroupBox

2019-09-16 16:30发布

问题:

I am looking for an event if the mouse is clicked outside of the groupBox in Qt. I tried FocusOutEvent but was not able to get the event:

ui.groupBox->installEventFilter(this); 

void myClass::focusOutEvent(QFocusEvent *event) { ui.groupBox->hide(); }

Any kind of help would be greatly appreciated!

回答1:

You have the following options:

  1. Subclass QGroupBox and override mousePressEvent()

  2. Install an event filter on that group box and catch QMouseEvents

  3. If you want to catch only right mouse clicks (context menu), implement a custom context menu handler.



回答2:

The problem is that the events of the monitored object are not forwarded to the native event handlers of the filter object such as focusOutEvent, but to a special virtual event function, i.e. eventFilter(QObject *obj, QEvent *event) as documented in installEventFilter. So, your event handler should look like this:

bool myClass::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui.groupBox && event->type () == QEvent::FocusOut)
        ui.groupBox->hide(); 
    return false;
}


标签: qt qgroupbox