使用自定義事件涉及到創建自己的QEvent的子類中,將接收的事件(通常是主窗口類)和一些代碼QObject的類中重寫自定義事件()是將事件從您的線索「發佈」到接收器。
我喜歡將事件發佈代碼作爲接收者類的一種方法實現。這樣,調用者只需知道接收對象而不是任何「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
可以是任意整數數據。
而不是QCustomeEvent,爲什麼不使用信號/插槽機制? – Arlen 2011-05-19 15:58:38
以什麼方式......我將如何從線程B調用線程A以執行函數...? – Goz 2011-05-19 16:10:32
Qt信號/插槽機制是線程安全的,可以跨線程使用。如果你不知道如何查找信號/插槽教程。 – Arlen 2011-05-19 16:23:32