简体   繁体   English

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

[英]How to run it on another Qt thread?

With Qthread in mind I tried the following but it seems everything is still running in the same thread.考虑到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小部件.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

Running I get the output:运行我得到输出:

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

Above output was from macOS but in Windows I got similar result.以上输出来自 macOS,但在 Windows 中我得到了类似的结果。

So what am I doing wrong?那么我做错了什么?

You cannot call the slot compute() directly, it will call it in the same thread as runs the code which called it (as you can see in the output).您不能直接调用插槽compute() ,它将在运行调用它的代码的同一线程中调用它(如您在输出中所见)。

You need to run the slot via signals/slots mechanism (or with invokeMethod() , but let's ignore this one).您需要通过信号/插槽机制(或使用invokeMethod()运行插槽,但让我们忽略这一点)。

Typically this is done by connecting thread's started() signal to the slot and then calling QThread::start() from the main thread.通常这是通过将线程的started()信号连接到插槽然后从主线程调用QThread::start()来完成的。 It will result in slot being called in the secondary thread just after the thread gets started.这将导致在线程启动后立即在辅助线程中调用插槽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM