Using custom events typically involves creating your own QEvent subclass, overriding customEvent () in the QObject class, which will receive the event (often this is the main window class) and some code that "sends" the event from your stream to the receiver.
I like to implement event publishing code as a receiver class method. Thus, the caller should know only about the recevier object, and not about the specifics of Qt. The caller will call this method, which will then essentially send the message to itself. We hope that the code below will become more clear.
// 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), m_customData1(customData1), m_customData2(customData2) { } int getCustomData1() const { return m_customData1; } int getCustomData2() const { return m_customData2; } private: int m_customData1; int m_customData2; }; public: void postMyCustomEvent(const int customData1, const int customData2); .... protected: void customEvent(QEvent *event); // This overrides QObject::customEvent() ... private: void handleMyCustomEvent(const MyCustomEvent *event);
customData1 and customData2 should demonstrate how you can pass some data in your event. They should not be int s.
I hope I haven’t left anything. With this in place, the code in some other thread just needs to get a pointer to the MainWindow object (call it MainWindow ) and call
mainWindow->postMyCustomEvent(1,2);
where, just for our example, 1 and 2 can be any integer data.
source share