QObject::moveToThread 并在该线程内执行成员函数
如果将 QObject
类型的对象移动到使用 QObject::moveToThread
的线程,则该对象接收的所有信号都在该线程内处理。但是,如果直接调用槽(object->theSlot()
),该调用仍然会阻塞。在线程内执行该调用并立即将控制权返回给调用线程的正常方法是什么?使用 QTimer
进行的黑客攻击不算在内。如果其他方法都失败,设置单一用途连接并再次删除它可能会被视为一种解决方案。
If an object of type QObject
is moved to a thread with QObject::moveToThread
, all signals that the object receives are handled inside that thread. However, if a slot is called directly (object->theSlot()
) that call will still block. What would be the normal way of executing that call inside the thread and returning control to the calling thread immediately? Hacks with QTimer
don't count. Setting up a single purpose connection and deleting it again might count as a solution if all else fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
QMetaObject::invokeMethod
并将 Qt::ConnectionType 设置为 Qt::QueuedConnectionYou could use
QMetaObject::invokeMethod
with Qt::ConnectionType set to Qt::QueuedConnection您可以使用 QFuture; QtConcurrent::run (Function function, ...) 在单独的线程内启动一些执行,然后使用
QFutureWatcher
获取结果。您不需要调用movetoThread
。基本上类似:
QtConcurrent::run
将安排该对象的方法在某个线程中运行。它是非阻塞的。另一方面,如果计算仍在进行,QFuture::result()
会阻塞,直到有结果为止。这就是为什么您需要另一个对象在计算结束时使用finished()
进行通知。我想不出更好的设计来解决 Qt 中的问题。You can use
QFuture<T> QtConcurrent::run ( Function function, ... )
to launch some execution inside a separate thread and then useQFutureWatcher
to get the result. You will not need to callmovetoThread
.Basically something like :
QtConcurrent::run
will schedule the method of this object to be ran in some thread. It is non-blocking. On the other hand,QFuture::result()
blocks until there is a result, if the computation is still ongoing. That's why you need the other object to notify when the computation is over usingfinished()
. I cannot think of a better design for your problem in Qt.