mythread.h文件
1 #ifndef MYTHREAD_H 2 #define MYTHREAD_H 3 #include <QThread> 4 5 class myThread : public QObject 6 { 7 Q_OBJECT 8 public: 9 explicit myThread(QObject *parent = 0); 10 //线程处理函数 11 void myTimeout(); 12 13 void setFlag(bool flag = true); 14 15 signals: 16 void mySignal(); 17 18 public slots: 19 20 private: 21 bool isStop; 22 }; 23 24 #endif // MYTHREAD_H
1 #include "mythread.h" 2 #include <QThread> 3 #include <QDebug> 4 5 6 myThread::myThread(QObject *parent) : QObject(parent) 7 { 8 isStop = false; 9 } 10 11 void myThread::myTimeout() 12 { 13 while( !isStop ) 14 { 15 16 QThread::sleep(1); 17 emit mySignal(); 18 19 20 qDebug() << "子线程号:" << QThread::currentThread(); 21 22 if(isStop) 23 { 24 break; 25 } 26 } 27 } 28 29 void myThread::setFlag(bool flag) 30 { 31 isStop = flag; 32 }
1 #ifndef WIDGET_H 2 #define WIDGET_H 3 #include "mythread.h" 4 #include <QWidget> 5 #include <QTimer> 6 #include <QThread> 7 #include <QDebug> 8 namespace Ui { 9 class Widget; 10 } 11 12 class Widget : public QWidget 13 { 14 Q_OBJECT 15 16 public: 17 explicit Widget(QWidget *parent = 0); 18 ~Widget(); 19 void dealSignal(); 20 void dealClose(); 21 22 signals: 23 void startThread(); //启动子线程的信号 24 25 private slots: 26 27 void on_start_clicked(); 28 29 void on_stop_clicked(); 30 31 private: 32 Ui::Widget *ui; 33 myThread *myT; 34 QThread *thread; 35 }; 36 37 #endif // WIDGET_H
1 #include "widget.h" 2 #include "ui_widget.h" 3 #include "mythread.h" 4 Widget::Widget(QWidget *parent) : 5 QWidget(parent), 6 ui(new Ui::Widget) 7 { 8 ui->setupUi(this); 9 myT = new myThread;//不能初始化指定父类myThread(this) 10 11 //创建子线程 12 thread = new QThread(this); 13 14 //把自定义线程加入到子线程中 15 myT->moveToThread(thread); 16 17 connect(myT, &myThread::mySignal, this, &Widget::dealSignal); 18 19 qDebug() << "主线程号:" << QThread::currentThread(); 20 21 connect(this, &Widget::startThread, myT, &myThread::myTimeout); 22 23 //窗口关闭时调用线程关闭,前提是线程要运行完当前任务 24 connect(this, &Widget::destroyed, this, &Widget::dealClose); 25 30 } 31 32 Widget::~Widget() 33 { 34 delete ui; 35 } 36 37 void Widget::dealClose() 38 { 39 on_stop_clicked(); 40 delete myT; 41 } 42 43 void Widget::dealSignal() 44 { 45 static int i = 0; 46 i++; 47 ui->lcdNumber->display(i); 48 } 49 50 void Widget::on_start_clicked() 51 { 52 if(thread->isRunning() == true) 53 { 54 return; 55 } 56 57 //启动线程,但是没有启动线程处理函数 58 thread->start(); 59 myT->setFlag(false); 60 61 //不能直接调用线程处理函数, 62 //直接调用,导致,线程处理函数和主线程是在同一个线程 63 //只能通过 signal - slot 方式调用 64 emit startThread(); 65 } 66 67 void Widget::on_stop_clicked() 68 { 69 if(thread->isRunning() == false) 70 { 71 return; 72 } 73 74 myT->setFlag(true); 75 thread->quit(); 76 thread->wait(); 77 }
原文:https://www.cnblogs.com/fuzhuoxin/p/12158488.html