标签:char 两种 col 转移 object RKE quit win space
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(); }
标签:char 两种 col 转移 object RKE quit win space
原文地址:https://www.cnblogs.com/nanqiang/p/10818609.html