Qt之子类发送消息给父类

例子:好比QWidget发送消息给QApplicationapp

在widget.cpp中重载event事件post

#include <qDebug>
 bool Widget::event(QEvent *e)
 {
     if(e->type() == QEvent::Close)  //由于Widget的父类是app
       {
           qDebug() << "User event is comming";
       }
       return QWidget::event(e);
 }

接收事件code

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    
    // 发送一个Event给MyWidget
    qDebug() << "begin send";
    a.postEvent(&w, new QEvent(QEvent::User));
  //  sendEvent,建议用postEvent
    qDebug() << "end send";
    return a.exec();
}

//能够在程序任意地方qApp.postEvent(&w, new QEvent(QEvent::User));
相关文章
相关标签/搜索