注意,MyTask不能有父对象,否则线程不能转移,只能在父线程中执行。
#pragma once
#include <QObject>
#include <QThread>
#include <QDebug>
class MyTask : public QObject
{
Q_OBJECT
signals:
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;
};