QtConcurrent::run 发出信号 [英] QtConcurrent::run emit signal

查看:267
本文介绍了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.

// https://github.com/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 发出信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆