Qt5创建自定义事件

使用自定义事件涉及到创建自己的QEvent的子类中,将接收的事件(通常是主窗口类)和一些代码QObject的类中重写自定义事件是将事件从您的事件“发布”到接收器。

// MainWindow.h 
... 
// Define your custom event identifier 
const QEvent::Type MY_CUSTOM_EVENT = static_cast<QEvent::Type>(QEvent::User + 1); 

// Define your custom event subclass 
class MyCustomEvent : public QEvent 
{ 
    public: 
     MyCustomEvent(const int customData1, const int customData2): 
      QEvent(MY_CUSTOM_EVENT), 
      _customData1(customData1), 
      _customData2(customData2) 
     { 
     } 

     int getCustomData1() const 
     { 
      return _customData1; 
     } 

     int getCustomData2() const 
     { 
      return _customData2; 
     } 

    private: 
     int _customData1; 
     int _customData2; 
}; 
// MainWindow.cpp 
... 

// 重写customEvent或event函数来接收事件
void MainWindow::customEvent(QEvent * event) 
{ 
    // When we get here, we've crossed the thread boundary and are now 
    // executing in the Qt object's thread 

    if(event->type() == MY_CUSTOM_EVENT) 
    { 
     handleMyCustomEvent(static_cast<MyCustomEvent *>(event)); 
    } 

    // use more else ifs to handle other custom events 
} 

void MainWindow::handleMyCustomEvent(const MyCustomEvent *event) 
{ 
    // Now you can safely do something with your Qt objects. 
    // Access your custom data using event->getCustomData1() etc. 
} 

创建事件:

QCoreApplication::postEvent(this, new MyCustomEvent(123, 456));

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注