QT-Qthread多线程

本文最后更新于:1 年前

开启子线程处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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();