我想在 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 发出信号
发布评论