简体   繁体   中英

Qt: capturing event before child

I have stackedWidget and I want to capture all mouseClickEvents of his childs, independendly of their types. They can be added and removed later (removed from stackedWidget, not deleted). How can I make this work?

You can install a Event Filter on all your child widgets, your event filter can be a new class or a existing class the important thing is it implements the eventFilter method and inherits from QObject

A example (Modified from Documenation)

bool FilterObject::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == textEdit) {
        if (event->type() == QEvent::mousePress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            qDebug() << "Ate mouse press" << mouseEvent->x() << " " << mouseEvent->y();
            return true;
        } else {
            return false;
        }
    } else {
        // pass the event on to the parent class
        return FilterObject::eventFilter(obj, event);
    }
}

Do the following to install the event filter after your widget is created

 FilterObject * filterObj = new FitlerObject(this);

 Q_FOREACH(QObject obj, pWin->children())
 {
     obj->installEventFilter(filterObj);
 }

You can find the full doco at http://qt-project.org/doc/qt-4.8/qobject.html#eventFilter and http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter

Here an explanation about how to get child controls events:

http://falsinsoft.blogspot.com/2014/04/qt-get-child-controls-events.html

Basically the way is the event filter as already suggested. However the "problem" is how to install the filter in case your window GUI is managed through the Qt Designer tool. In this case you don't have direct control to the code creating the child controls and you need to use the alternative way to get the "ChildAdded" events of your main object for install the filter in each new child controls just added as explained in the link above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM