Qt 多线程使用moveToThread
Posted nanqiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt 多线程使用moveToThread相关的知识,希望对你有一定的参考价值。
Qt有两种多线程的方法,其中一种是继承QThread的run函数,
另外一种是把一个继承于QObject的类用moveToThread函数转移到一个Thread里。
Qt4.8之前都是使用继承QThread的run这种方法,但是Qt4.8之后,Qt官方建议使用第二种方法。
//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(); }
以上是关于Qt 多线程使用moveToThread的主要内容,如果未能解决你的问题,请参考以下文章
qt中通过重写run方法创建线程与通过movetothread方法有啥区别
QT5 关于object基类实现的多线程操作,movetothread方法的使用