Goz*_*Goz 4 c++ qt postmessage
我有一个RPC线程从该线程回调给我.我需要以某种方式通知Qt它需要从主线程进行函数调用.在直接Windows中我可以通过使用自定义消息然后将该消息发布到消息队列来完成此操作,例如,我可以创建WM_CALLFUNCTION消息并传递函数指针wParam和参数(类指针)lParam.
有谁知道如何用Qt做到这一点?我遇到过QCustomEvent但我不知道如何使用它或如何处理它.任何帮助将非常感谢!
编辑:
最后我选择了QMetaObject :: invokeMethod,它完美无缺.
使用自定义事件通常涉及创建自己的QEvent的子类,覆盖CustomEvent的()中,将接收的事件(通常是主窗口类)和一些代码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);
Run Code Online (Sandbox Code Playgroud)
该customData1和customData2在那里演示如何可能会通过一些数据一起在你的事件.他们不一定是ints.
// 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.
}
Run Code Online (Sandbox Code Playgroud)
我希望我没有遗漏任何东西.有了这个,其他一些线程中的代码只需要获取指向MainWindow对象的指针(让我们调用它mainWindow)并调用
mainWindow->postMyCustomEvent(1,2);
Run Code Online (Sandbox Code Playgroud)
在那里,只是我们的例子中,1并且2可以是任意整数数据.
在Qt 3中,从非GUI线程与GUI线程通信的常用方法是将自定义事件发布到GUI线程中的QObject.在Qt 4中,这仍然有效,并且可以推广到一个线程需要与具有事件循环的任何其他线程进行通信的情况.
为了简化编程,Qt 4还允许您跨线程建立信号 - 插槽连接.在幕后,这些连接是使用事件实现的.如果信号具有任何参数,则这些参数也存储在事件中.和以前一样,如果发送者和接收者生活在同一个线程中,Qt会进行直接的函数调用.
- http://doc.qt.nokia.com/qq/qq14-threading.html#signalslotconnectionsacrossthreads