基本思想
- 在主线程中,哪里需用多线程,就在哪里创建一个QThread实例;
- 把耗时操作封装到一个继承于QObject的子类(这里叫做工作类Worker)槽函数中;
- 创建QThread实例和Worker实例,建立他们之间的信号和槽关系;
- 调用Worker实例的moveToThread(QThread * thread)函数,将它移动到创建的QThread线程中去;
- 最后,执行QThread线程的start()方法。
工作类
worker.h
1 #ifndef WORKER_H
2 #define WORKER_H
3 #include <QObject>
4 class Worker : public QObject
5 {
6 Q_OBJECT
7 public:
8 explicit Worker(QObject *parent = 0);
9 signals:
10 void complete();
11 public slots:
12 void doLongTimeWork();//耗时操作
13 };
14 #endif // WORKER_H
worker.cpp
1 #include "worker.h"
2 #include <QDebug>
3 #include <QThread>
4 Worker::Worker(QObject *parent) : QObject(parent)
5 {
6
7 }
8 void Worker::doLongTimeWork()
9 {
10 qDebug()<<__LINE__<<__FUNCTION__<<" - enter";
11 qint64 count = 100;
12 while(count--){
13 QThread::msleep(10);
14 qDebug()<<__LINE__<<__FUNCTION__<<"count = "<<count;
15 }
16 emit complete();
17 qDebug()<<__LINE__<<__FUNCTION__<<" - leave";
18 }
使用方法
1 void MainWindow::on_pushButtonDoWork_clicked()
2 {
3 Worker* worker = new Worker();
4 QThread* thread = new QThread();
5 //当线程启动时,执行Worker类的耗时函数doLongTimeWork()
6 connect(thread,SIGNAL(started()),worker,SLOT(doLongTimeWork()));
7 //当耗时函数执行完毕,发出complete()信号时,删除worker实例
8 connect(worker,SIGNAL(complete()),worker,SLOT(deleteLater()));
9 //当worker对象实例销毁时,退出线程
10 connect(worker,SIGNAL(destroyed(QObject*)),thread,SLOT(quit()));
11 //当线程结束时,销毁线程对象实例
12 connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
13 //移动worker对象实例到线程中
14 worker->moveToThread(thread);
15 //启动线程
16 thread->start();
17 }