Call QtConcurrent::run as slot
connect
has implicit Qt::ConnectionType parameter. It will be defined as Qt::QueuedConnection
when sender and receiver are in different threads. You can use QObject::moveToThread
to move worker to another thread.
If for some reason you want use QtConcurrent::run
here - you can use it inside func1
implementation.
Check both versions:
class Worker : public QObject {
public:
void DoSlowCalculation() {
qDebug() << "Worker::DoSlowCalculation thread:" << QThread::currentThreadId();
QThread::msleep(2000); // 2 sec
qDebug() << "Worker::DoSlowCalculation finished";
}
};
class ConcurrentExecutor : public QObject {
public:
void DoSlowCalculation() {
qDebug() << "ConcurrentExecutor::DoSlowCalculation thread:" << QThread::currentThreadId();
QThread::msleep(2000); // 2 sec
qDebug() << "ConcurrentExecutor::DoSlowCalculation finished";
}
void DoSlowCalculationConcurrent() {
QtConcurrent::run(this, &ConcurrentExecutor::DoSlowCalculation);
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
qDebug() << "Main thread:" << QThread::currentThreadId();
QThread worker_thread;
Worker worker;
worker.moveToThread(&worker_thread);
worker_thread.start();
QPushButton btn;
btn.setText("Click to perform slow calculation");
QObject::connect(&btn, &QAbstractButton::clicked, &worker,
&Worker::DoSlowCalculation);
ConcurrentExecutor concurr_executor;
QObject::connect(&btn, &QAbstractButton::clicked, &concurr_executor,
&ConcurrentExecutor::DoSlowCalculationConcurrent);
worker_thread.start();
QObject::connect(&app, &QCoreApplication::aboutToQuit, &worker_thread,
&QThread::quit);
btn.show();
return app.exec();
}
P.S. Strongly suggest to stop using SIGNAL and SLOT macros, that's Qt4 way to connect. More info on this topic here.