QT [C++] 中线程实现的几个错误

Several Error with Implementing of Threads in QT [C++]

我是在 QT 中实现线程的新手,甚至在多次阅读文档和观看视频后,我还是遇到了一些甚至 Google 都无法帮助我解决的错误。

thread.cpp:14: error: C2440: "Initialisierung": "QFuture" kann nicht in "QFuture" konvertiert werden

错误代码是德语,尝试更改 QT 语言,但没有更改错误的语言。如果需要我可以翻译。

似乎错误发生在这个 QFuture<int> future = QtConcurrent::run(&Thread::GenerateTable); 命令中,甚至以为我像 QT 文档中那样写了它 1:1。 这是我想放入线程中的代码,如您所见,它正在将一些数字写入文件,这大约需要一分钟。

Thread.h

#ifndef THREAD_H
#define THREAD_H

#include <QObject>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>


class Thread : public QObject
{
    Q_OBJECT
public:
    explicit Thread(QObject *parent = nullptr);

    static bool start();

private:
   int GenerateTable();
};

#endif // THREAD_H

Thread.cpp

#include "thread.h"

Thread::Thread(QObject *parent) : QObject(parent)
{

}

bool Thread::start()
{

    QFuture<int> future = QtConcurrent::run(&Thread::GenerateTable);
    if (future.result() == 0){
        return true;
    }
    else
        return false;
}

int Thread::GenerateTable(){

    QString Path = QDir::currentPath();
    QFile file(Path + "/Table.csv");
    if (!file.open(QFile::WriteOnly | QFile::Text)){
        return -1;
    }
    else{
        QTextStream stream(&file);
        constexpr uint64_t upper = 10'000'000;
        QVector<uint64_t> rando(upper);

        std::iota(rando.begin(), rando.end(), 1);
        std::shuffle(rando.begin(), rando.end(),
                     std::mt19937(std::random_device{}()));

        for (uint32_t i = 0; i < 10'000'000; ++i) {
          stream << rando[i] << ',' << '\n';
        }
        return 0;
    }
}

Thread::GenerateTable() 是一个 成员函数 。它需要一个对象来处理。您正在从(静态)Thread::start() 调用它(呃 .. 将其传递给 QtConcurrent::run())并且没有 Thread 对象可言。

虽然您已经标记了 Qt6,但我会指出 Qt5 documentation 用于调用成员函数:您可以传递需要从某处分配的对象(指针)。