如何在另一个Qt线程上运行?



考虑到Qthread,我尝试了以下操作,但似乎所有操作仍在同一线程中运行。

main.cpp

#include "widget.h"
#include <QApplication>
#include "core.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
Core core;
Widget w(core);
w.show();
return a.exec();
}

func.h

#ifndef FUNC_H
#define FUNC_H
#include <QDebug>
#include <QThread>
class Func : public QObject
{
Q_OBJECT
public:
explicit Func()
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
}
void compute()
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
}
};
#endif // FUNC_H

core.h

#ifndef CORE_H
#define CORE_H
#include <QObject>
#include "func.h"
class Core : public QObject
{
Q_OBJECT
QThread thread;
Func* func = nullptr;
public:
explicit Core(QObject *parent = nullptr)
{
func = new Func();
func->moveToThread(&thread);
connect(&thread, &QThread::finished, func, &QObject::deleteLater);
thread.start();
}
~Core() {
thread.quit();
thread.wait();
}
public slots:
void compute(){func->compute();}
signals:
};
#endif // CORE_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "core.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(Core& core)
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
core.compute(); // This should run on a different thread ?
}
};
#endif // WIDGET_H

运行得到输出:

int main(int, char **) 0x107567e00
Func::Func() 0x107567e00
Widget::Widget(Core &) 0x107567e00
void Func::compute() 0x107567e00

上面的输出来自macOS,但在Windows中我得到了类似的结果。

我做错了什么?

您不能直接调用slotcompute(),它将在运行调用它的代码的同一线程中调用它(如您在输出中所看到的)。

您需要通过信号/插槽机制运行插槽(或者使用invokeMethod(),但我们忽略这个)。

通常这是通过连接线程的started()信号到插槽,然后从主线程调用QThread::start()来完成的。这将导致在线程启动后,在次要线程中调用slot。

最新更新