使用自定义事件通常涉及创建自己的 QEvent 子类,覆盖将接收事件(通常是主窗口类)的 QObject 类中的 customEvent() 以及将事件从线程“发布”到接收器的一些代码。
我喜欢将事件发布代码实现为接收器类的方法。这样,调用者只需要知道接收者对象而不是任何“Qt”细节。调用者将调用此方法,然后本质上将向其自身发布一条消息。希望下面的代码会让它更清晰。
// 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
。customData2
他们不必是int
s。
// MainWindow.cpp
...
void MainWindow::postMyCustomEvent(const int customData1, const int customData2)
{
// This method (postMyCustomEvent) can be called from any thread
QApplication::postEvent(this, new MyCustomEvent(customData1, customData2));
}
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.
}
我希望我没有遗漏任何东西。有了这个,其他线程中的代码只需要获取一个指向MainWindow
对象的指针(让我们称之为mainWindow
)并调用
mainWindow->postMyCustomEvent(1,2);
其中,仅用于我们的示例,1
并且2
可以是任何整数数据。