演示:
#include <QCoreApplication>
#include <QThread>
#include <QObject>
#include <QDebug>// 子线程类
class Worker : public QObject {Q_OBJECT
public slots:void processData(int data) {qDebug() << "Processing data in thread:" << QThread::currentThread();// 模拟耗时操作QThread::sleep(2);qDebug() << "Finished processing data:" << data;}
};int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);// 创建子线程对象QThread workerThread;Worker worker;// 将worker对象移动到子线程worker.moveToThread(&workerThread);// 连接信号和槽QObject::connect(&workerThread, &QThread::started, [&worker]() {for (int i = 0; i < 5; ++i) {emit worker.processData(i);QThread::sleep(1); // 模拟主线程的其他工作}});// 启动子线程workerThread.start();// 主线程继续执行其他任务for (int i = 0; i < 5; ++i) {qDebug() << "Main thread working...";QThread::sleep(1); // 模拟主线程的其他工作}// 等待子线程完成workerThread.quit();workerThread.wait();return a.exec();
}#include "main.moc"