使用自定义事件涉及到创建自己的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