使用 Qt 创建自定义消息/事件
我有一个 RPC 线程正在从该线程回调我。我需要以某种方式通知 Qt 它需要从主线程进行函数调用。在直接 Windows 中,我可以通过使用自定义消息然后将该消息发布到消息队列来完成此操作,例如,我可以创建一个 WM_CALLFUNCTION
消息并通过 wParam
传递函数指针> 和通过lParam
的参数(类指针)。
有谁知道我如何用 Qt 做到这一点?我遇到过 QCustomEvent
但我不知道如何使用它或如何处理它。任何帮助将不胜感激!
编辑:
最后我选择了 QMetaObject::invokeMethod工作完美。
I have an RPC thread that is calling back to me from that thread. I need to somehow inform Qt that it needs to make a function call from the main thread. In straight Windows I could do this by using a custom message and then posting that message to the message queue, e.g., I could create a WM_CALLFUNCTION
message and pass the function pointer through wParam
and the parameter (class pointer) through lParam
.
Has anyone an idea how I could do this with Qt? I've come across QCustomEvent
but I have no idea how to use it or how to process it. Any help would be hugely appreciated!
Edit:
In the end I went with QMetaObject::invokeMethod which works perfectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用自定义事件通常涉及创建您自己的 QEvent 子类、重写将接收事件的 QObject 类(通常是主窗口类)中的 customEvent() 以及将事件从线程“发布”到接收器的一些代码。
我喜欢将事件发布代码实现为接收器类的方法。这样,调用者只需了解接收者对象,而不需要了解任何“Qt”细节。调用者将调用此方法,然后该方法将向其自身发送一条消息。希望下面的代码能让它更清楚。
customData1
和customData2
用于演示如何在事件中传递一些数据。它们不必是int
。我希望我没有遗漏任何东西。有了这个,其他线程中的代码只需要获取指向
MainWindow
对象的指针(我们称之为mainWindow
)并调用where,仅对于我们的示例来说,< code>1 和
2
可以是任何整数数据。Using custom events generally involves creating your own QEvent subclass, overriding customEvent() in the QObject class that will receive the event (often the main window class) and some code that "posts" the event from your thread to the receiver.
I like to implement the event posting code as a method of the receiver class. That way, the caller only has to know about the recevier object and not any of the "Qt" specifics. The caller will invoke this method which will then essentially post a message to itself. Hopefully the code below will make it clearer.
The
customData1
andcustomData2
are there to demonstrate how you might pass some data along in your event. They don't have to beint
s.I hope I didn't leave anything out. With this in place, code in some other thread just needs to get a pointer to a
MainWindow
object (let's call itmainWindow
) and callwhere, just for our example,
1
and2
can be any integer data.--
http://doc.qt.nokia.com/qq/qq14-threading.html#signalslotconnectionsacrossthreads< /a>
--
http://doc.qt.nokia.com/qq/qq14-threading.html#signalslotconnectionsacrossthreads