gpt4 book ai didi

c++ - Qt: 如何正确使用 moveToThread(this)?

转载 作者:行者123 更新时间:2023-11-30 01:14:27 25 4
gpt4 key购买 nike

我有这样一个类:

class myClass:public QThread

然后在它的构造函数中我做了:

myClass::myClass(){
moveToThread(this);
...
}

看起来所有的成员槽实际上都在工作线程上工作。但是在这种情况下,我怎么能在解构期间停止线程呢?

最佳答案

只是不要那样做线程。

使用 moveToThread() 的正确方法在 Qt 文档中有描述:

class Worker : public QObject
{
Q_OBJECT

public slots:
void doWork(const QString &parameter) {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}

signals:
void resultReady(const QString &result);
};

class Controller : public QObject
{
Q_OBJECT
QThread workerThread;
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &Controller::operate, worker, &Worker::doWork);
connect(worker, &Worker::resultReady, this, &Controller::handleResults);
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
public slots:
void handleResults(const QString &);
signals:
void operate(const QString &);
};

或者通过继承QThread,比如:

class WorkerThread : public QThread
{
Q_OBJECT
void run() Q_DECL_OVERRIDE {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals:
void resultReady(const QString &s);
};

void MyObject::startWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread(this);
connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
workerThread->start();
}

但两者不能同时出现。关于该主题的更多信息 here

关于c++ - Qt: 如何正确使用 moveToThread(this)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com