概述
使用 QObject::moveToThread() 方法,可以把一个继承自 QObject 的对象交给一个 QThread 对象,然后再调用 QThread 的 start() 函数使其全权处理事件循环,当我们需要让子线程执行某个任务,只需要发出对应的信号就可以。
而继承 QThread 实现多线程方法,只能执行 run() 函数中的任务。使用 moveToThread 可以定义多个槽函数,用相应的信号触发即可。
代码示例
①.定义一个继承自 QObject 的对象
class WorkObject : public QObject
{
Q_OBJECT
public:
WorkObject(QObject *parent = nullptr);
~WorkObject();
signals:
void workStart();//工作开始
void workFinished();//工作完成
private:
void doWork();
public slots:
void starWork();//开始工作
};
WorkObject::WorkObject(QObject *parent)
: QObject(parent)
{
}
WorkObject::~WorkObject()
{
qDebug() << "WorkObject 销毁" << endl;
}
void WorkObject::doWork()
{
for (int i = 0; i < 1000; ++i)
{
qDebug() << i << endl;
}
emit workFinished();
}
void WorkObject::starWork()
{
emit workStart();
doWork();
}
②.使用 moveToThread 转移线程
WorkObject * workObject = new WorkObject();//工作对象
QThread * workThread = new QThread();//工作线程
//转移线程
workObject->moveToThread(workThread);
//开始工作
QObject::connect(workThread, &QThread::started, workObject, &WorkObject::starWork);
//工作对象工作结束,停止线程
QObject::connect(workObject, &WorkObject::workFinished, workThread, [&]() {
workThread->quit();
workThread->wait();
});
//工作线程停止,销毁工作对象
QObject::connect(workThread, &QThread::finished, workObject, &WorkObject::deleteLater);
//工作对象销毁,销毁工作线程
QObject::connect(workObject, &WorkObject::destroyed, workThread, &QThread::deleteLater);
//线程销毁
QObject::connect(workThread, &QThread::destroyed, [&]() {
qDebug() << "workThread 销毁" << endl;
});
//启动线程
workThread->start();
代码运行结果如下: