继承 QObject [推荐]

最后更新于:2022-04-02 02:13:03

[TOC] ## 概述 1. 利用继承QObject方法创建多线程,主要的步骤有一下几点:(注意:退出线程循环后,还要调用QThread::quit()函数,该线程才会触发`QThread::finished()`信号) **流程** 1. 首先创建一个类MyThread,基类为QObject。 2. 在类MyThread中创建一个槽函数,用于运行多线程里面的代码。所有耗时代码,全部在这个槽函数里面运行。 3. 实例一个QThread线程对象(容器),将类MyThread的实例对象转到该容器中,用函数void QObject::moveToThread(QThread *thread); ``` myObjectThread->moveToThread(firstThread); ``` 4. 用一个信号触发该多线程槽函数,比如用QThread::started()信号。 ``` connect(firstThread,SIGNAL(started()),myObjectThread,SLOT(startThreadSlot())); ``` 5. 用信号QThread::finished绑定槽函数QThread::deleteLatater(),在线程退出时,销毁该线程和相关资源。 ``` connect(firstThread,SIGNAL(finished()),firstThread,SLOT(deleteLater())); ``` 6. 所有线程初始化完成后,启动函数QThread::start()开启多线程,然后自动触发多线程启动信号QThread::started()。 ## 示例
mythread.h ``` #ifndef MYTHREAD_H #define MYTHREAD_H #include #include class MyThread : public QObject { public: explicit MyThread(QObject *parent = nullptr); void closeThread(); public slots: void startThreadSLot(); private: volatile bool isStop; }; #endif ```

widget.h ``` #ifndef WIDGET_H #define WIDGET_H #include "mythread.h" #include #include class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = nullptr); void createView(); public slots: void openThreads(); void closeThreads(); void finishedThread(); signals: private: MyThread* myThread; QThread* thread; QVBoxLayout *layout; }; #endif // WIDGET_H ```

mythread.cpp ``` #include "mythread.h" MyThread::MyThread(QObject *parent) : QObject(parent){ isStop=false; } void MyThread::closeThread(){ isStop=true; } void MyThread::startThreadSLot() { while(true){ if(isStop){ return ; } qDebug()<<"MyThread::startThreadSlot QThread::currentThreadId()=="<
widget.cpp ``` #include "widget.h" #include #include Widget::Widget(QWidget *parent) : QWidget(parent) { createView(); thread = new QThread; } void Widget::createView() { qDebug()<<"启动进程"; layout=new QVBoxLayout(this); QPushButton *openThreadBtn = new QPushButton(tr("打开线程")); QPushButton *closeThreadBtn = new QPushButton(tr("关闭线程")); layout->addWidget(openThreadBtn); layout->addWidget(closeThreadBtn); layout->addWidget(new QTextEdit()); layout->addStretch(); connect(openThreadBtn,&QPushButton::clicked,this,&Widget::openThreads); connect(closeThreadBtn,&QPushButton::clicked,this,&Widget::closeThreads); } void Widget::openThreads() { qDebug()<isRunning()){ myThread->moveToThread(thread); connect(thread,&QThread::finished,myThread,&MyThread::deleteLater); connect(thread,&QThread::started,myThread,&MyThread::startThreadSLot); thread->start(); qDebug()<<"QThread::currentThreadId() "<isRunning()){ myThread->closeThread(); myThread=nullptr; thread->quit(); thread->wait(); } } void Widget::finishedThread() { qDebug()<<"多线程触发了"; } ```

main.cpp ``` int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget widget; widget.resize(500,500); widget.show(); return a.exec(); } ```


';