本文主要是介绍Qt moveToThread,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注意,MyTask不能有父对象,否则线程不能转移,只能在父线程中执行。
#pragma once#include <QObject>
#include <QThread>
#include <QDebug>class MyTask : public QObject
{Q_OBJECTsignals:void sigResult(const QString &result);public slots:void slotDoing(const QString &val){qDebug() << "Worker thread id:" << this->thread()->currentThreadId();QString newVal;foreach (QChar c, val) {newVal.insert(0, c);}emit sigResult(newVal);QThread::sleep(3);}
};class Controller : public QObject
{Q_OBJECT
public:Controller(QObject *parent=0) : QObject(parent){qDebug() << "Controller thread id:" << this->thread()->currentThreadId();MyTask *task = new MyTask();task->moveToThread(&m_taskThread);connect(&m_taskThread, &QThread::finished, task, &QObject::deleteLater);connect(this, &Controller::sigStart, task, &MyTask::slotDoing);connect(task, &MyTask::sigResult, this, &Controller::slotResult);m_taskThread.start();}~Controller(){m_taskThread.quit();m_taskThread.wait(10000);qDebug() << "exit...";}signals:void sigStart(const QString &val);private slots:void slotResult(const QString &result){qDebug() << result;}private:QThread m_taskThread;
};
这篇关于Qt moveToThread的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!