[英]How to run it on another Qt thread?
考虑到Qthread ,我尝试了以下操作,但似乎所有内容仍在同一线程中运行。
主程序
#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();
}
函数文件
#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
核心文件
#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
小部件.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 中我得到了类似的结果。
那么我做错了什么?
您不能直接调用插槽compute()
,它将在运行调用它的代码的同一线程中调用它(如您在输出中所见)。
您需要通过信号/插槽机制(或使用invokeMethod()
运行插槽,但让我们忽略这一点)。
通常这是通过将线程的started()
信号连接到插槽然后从主线程调用QThread::start()
来完成的。 这将导致在线程启动后立即在辅助线程中调用插槽。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.