QObject::moveToThread 并在该线程内执行成员函数

发布于 2024-12-29 03:13:43 字数 261 浏览 1 评论 0原文

如果将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

慵挽 2025-01-05 03:13:43

您可以使用 QMetaObject::invokeMethod 并将 Qt::ConnectionType 设置为 Qt::QueuedConnection

You could use QMetaObject::invokeMethod with Qt::ConnectionType set to Qt::QueuedConnection

離人涙 2025-01-05 03:13:43

您可以使用 QFuture; QtConcurrent::run (Function function, ...) 在单独的线程内启动一些执行,然后使用 QFutureWatcher 获取结果。您不需要调用movetoThread

基本上类似:

QFutureWatcher<T>* watch = new QFuture(0);
connect(watch, SIGNAL(finished()), this, SLOT(handleResult()));
QFuture<T> future = QtConcurrent::run( myObj, &QMyObject::theSlot(), args...);
watch.setFuture(future);
....

//slot
private void handleResult(){
  if(future->isCancelled())
     return;  
  T mydata = watch->future()->result();
  // use your data as you want
}

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 use QFutureWatcher to get the result. You will not need to call movetoThread.

Basically something like :

QFutureWatcher<T>* watch = new QFuture(0);
connect(watch, SIGNAL(finished()), this, SLOT(handleResult()));
QFuture<T> future = QtConcurrent::run( myObj, &QMyObject::theSlot(), args...);
watch.setFuture(future);
....

//slot
private void handleResult(){
  if(future->isCancelled())
     return;  
  T mydata = watch->future()->result();
  // use your data as you want
}

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 using finished(). I cannot think of a better design for your problem in Qt.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文