簡體   English   中英

如何在另一個 Qt 線程上運行它?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM