The basic idea
- In the main thread, where the need to use multiple threads, created a QThread instance where;
- The operation of the Packaging consuming a subclass of QObject inherited (referred to herein as the Worker work classes) channel function;
- Creating QThread instances and Worker instance, signals and slots to establish the relationship between them;
- Call the Worker instance moveToThread (QThread * thread) function, move it to QThread threads created to go;
- Finally, the execution start QThread thread () method.
Working class
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 }
Instructions
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 }