QtConcurrent::run 发出信号

编程入门 行业动态 更新时间:2024-10-11 15:17:49
本文介绍了QtConcurrent::run 发出信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在 Qt 中从我用 QtConcurrent::run 调用的函数发出一个信号

I would like to emit a signal in Qt, from a function that I called with QtConcurrent::run

这可能吗?似乎我的插槽永远不会被调用.所有的信号、槽和函数都是同一个类对象的一部分.我尝试在主线程和从线程中建立连接.我真的不在乎信号和插槽是否在同一个线程中,我只是想让它发生.

Is this possible? It seems like my slot never gets called. All of the signals, slots, and functions are part of the same class object. I have tried making the connection in the Master thread, and in the slave thread. I dont really care if the signal and slot are in the same thread or not, I just want to get it to happen.

谢谢

推荐答案

以下在 Qt 4.8.7 中工作正常.该信号从工作线程发出,并在主线程中消耗.我们断言槽在主线程中运行,函子在工作线程中运行.

The below works just fine in Qt 4.8.7. The signal is emitted from the worker thread, and consumed in the main thread. We assert that the slot runs in the main thread, and the functor runs in the worker thread.

// github/KubaO/stackoverflown/tree/master/questions/concurrent-emit-qt4-7114421 #include <QtCore> class Helper : public QObject { Q_OBJECT public: int n = 0; Q_SLOT void increment() { Q_ASSERT(QThread::currentThread() == qApp->thread()); n++; } }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); Helper helper; Q_ASSERT(helper.n == 0); QtConcurrent::run([&]{ Q_ASSERT(QThread::currentThread() != qApp->thread()); QObject src; QObject::connect(&src, SIGNAL(destroyed(QObject*)), &helper, SLOT(increment())); QObject::connect(&src, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); }); app.exec(); Q_ASSERT(helper.n == 1); } #include "main.moc"

在 Qt 5 中,您不需要帮助类来证明它的工作原理:

In Qt 5, you don't need the helper class to demonstrate that it works:

#include <QtConcurrent> int main(int argc, char **argv) { QCoreApplication app(argc, argv); int n = 0; Q_ASSERT(n == 0); QtConcurrent::run([&]{ Q_ASSERT(QThread::currentThread() != qApp->thread()); QObject src; QObject::connect(&src, &QObject::destroyed, &app, [&]{ Q_ASSERT(QThread::currentThread() == qApp->thread()); n ++; qApp->quit(); }); }); app.exec(); Q_ASSERT(n == 1); }

更多推荐

QtConcurrent::run 发出信号

本文发布于:2023-10-09 05:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474838.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:信号   QtConcurrent   run

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!