标签:out ati define str protected color ted 头文件 signal
1 //mythread.cpp 2 3 #include "mythread.h" 4 5 MyThread::MyThread(QObject *parent) : QThread(parent) 6 { 7 8 } 9 10 void MyThread::run() 11 { 12 //很复杂的数据处理 13 //需要耗时5s 14 sleep(5); 15 emit isDone(); 16 }
//mythread.h #ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> class MyThread : public QThread { Q_OBJECT public: explicit MyThread(QObject *parent = 0); protected: void run(); signals: void isDone(); public slots: }; #endif // MYTHREAD_H
//mywidget.cpp #include "mywidget.h" #include "ui_mywidget.h" #include <QThread> #include <QDebug> MyWidget::MyWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MyWidget) { ui->setupUi(this); myTimer = new QTimer(this); connect(myTimer, &QTimer::timeout, this, &MyWidget::dealTimeout); //分配空间 thread = new MyThread(this); connect(thread, &MyThread::isDone, this, &MyWidget::dealDone); //当按窗口右上角x时,窗口触发destroyed() connect(this, &MyWidget::destroyed, this, &MyWidget::stopThread) } void MyWidget::stopThread() { //停止线程 thread->quit(); //等待线程处理完手头动作 thread->wait(); } void MyWidget::dealDone() { qDebug() << "it is over"; myTimer->stop(); //关闭定时器 } void MyWidget::dealTimeout() { static int i = 0; i++; //设置lcd的值 ui->lcdNumber->display(i); } MyWidget::~MyWidget() { delete ui; } void MyWidget::on_pushButton_clicked() { //如果定时器没有工作 if(myTimer->isActive() == false) { myTimer->start(100); } //启动线程,处理数据 thread->start(); }
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> #include <QTimer> //定时器头文件 #include "mythread.h" //线程头文件 namespace Ui { class MyWidget; } class MyWidget : public QWidget { Q_OBJECT public: explicit MyWidget(QWidget *parent = 0); ~MyWidget(); void dealTimeout(); //定时器槽函数 void dealDone(); //线程结束槽函数 void stopThread(); //停止线程槽函数 private slots: void on_pushButton_clicked(); private: Ui::MyWidget *ui; QTimer *myTimer; //声明变量 MyThread *thread; //线程对象 }; #endif // MYWIDGET_H
标签:out ati define str protected color ted 头文件 signal
原文地址:https://www.cnblogs.com/wangbin-heng/p/9581814.html