Qt有两种多线程的方法,其中一种是继承QThread的run函数,
另外一种是把一个继承于QObject的类用moveToThread函数转移到一个Thread里。
Qt4.8之前都是使用继承QThread的run这种方法,但是Qt4.8之后,Qt官方建议使用第二种方法。
具体的使用步骤如下:
1.从QObject派生一个类,将耗时的工作写在该类的槽函数中。
2.将派生类对象移动到一个QThread中,该线程需要start。(这一步使用moveToThread)
3.通过信号连接派生类的槽函数,并通过信号触发槽函数。(槽函数在子线程中执行)
//tes.h #ifndef TES_H #define TES_H #include <QCoreApplication> #include <QDebug> #include <QThread> #include <QString> #include <QObject> class Worker:public QObject { Q_OBJECT public: explicit Worker(QObject *parent=0); ~Worker(); signals: void sig_finish(); public slots: void slot_dowork(); }; #endif // TES_H
//tes.cpp #include "tes.h" Worker::Worker(QObject *parent):QObject(parent) { qDebug()<<"worker()"; } Worker::~Worker() { qDebug()<<"~worker()"; } void Worker::slot_dowork() { qDebug()<< "do work,thread id = " << QThread::currentThreadId(); emit sig_finish(); }
//mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "tes.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void dowork(); private: Ui::MainWindow *ui; Worker *m_pworker; QThread *m_pthread; signals: void sig_dowork(); public slots: void slot_finish(); }; #endif // MAINWINDOW_H
//mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { qDebug()<<"mainwindow()"; ui->setupUi(this); m_pworker = new Worker(); m_pthread = new QThread(); m_pworker->moveToThread(m_pthread); qDebug()<< "start,thread id = " << QThread::currentThreadId(); connect(m_pthread, &QThread::finished, m_pworker, &QObject::deleteLater); connect(this,SIGNAL(sig_dowork()),m_pworker,SLOT(slot_dowork())); connect(m_pworker,SIGNAL(sig_finish()),this,SLOT(slot_finish())); } MainWindow::~MainWindow() { qDebug()<<"~mainwindow()"; delete ui; m_pthread->quit(); m_pthread->wait(); } void MainWindow::dowork() { m_pthread->start(); emit sig_dowork(); } void MainWindow::slot_finish() { qDebug()<< "finish,thread id = " << QThread::currentThreadId(); }
//main.cpp #include <QCoreApplication> #include <QDebug> #include <QThread> #include <QString> #include <QObject> #include <QApplication> #include "tes.h" #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); w.dowork(); return a.exec(); }
来源:https://www.cnblogs.com/nanqiang/p/10818609.html