知识点
- 大量的数据处理任务放到子线程里面
- 线程创建
- 线程回收
- 线程处理函数内部,不允许操作图形界面
- 子线程处理一个死循环任务,通过改变标志位,让其退出死循环
- 子线程处理结束后,发送一个delDone信号让其主线程捕捉,触发槽函数
完整项目github地址:
https:
结果演示
线程创建流程图
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QThread>
#include <QDebug>
#define cout qDebug() << "[" << __FILE__ <<":" << __LINE__ << "]"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
myThread=new MyThread(this);
myThread->setIsStop(false);
bool ans=myThread->getStopValue();
cout<<ans;
connect(&myTimer,&QTimer::timeout,this,&Widget::delTimer);
connect(myThread,&MyThread::delDone,this,&Widget::myThreadDone);
connect(this,&Widget::destroyed,this,&Widget::killMyThread);
}
void Widget::killMyThread(){
myThread->setIsStop(true);
myThread->quit();
myThread->wait();
cout<<"关闭主窗口,线程资源回收";
}
void Widget::delTimer(){
static int i = 0;
ui->lcdNumber->display(i);
i++;
}
void Widget::myThreadDone(){
cout<<"线程处理结束,关闭定时器";
myTimer.stop();
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
if(!myTimer.isActive()){
myTimer.start(20);
}
if(myThread->isRunning()){
return;
}
myThread->start();
}
void Widget::on_buttonClose1_clicked()
{
if(!myThread->isRunning()){
return;
}
myThread->setIsStop(true);
Widget::myThreadDone();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
#include "mythread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_clicked();
void on_buttonClose1_clicked();
private:
Ui::Widget *ui;
QTimer myTimer;
MyThread *myThread;
private:
void delTimer();
void myThreadDone();
void killMyThread();
};
#endif
mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
isStop=false;
}
void MyThread::run(){
while (!isStop) {
sleep(1);
qDebug() << "子线程号:" << QThread::currentThread();
if(isStop){
break;
}
}
emit delDone();
}
bool MyThread::getStopValue(){
return isStop;
}
void MyThread::setIsStop(bool flag){
isStop=flag;
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
public:
bool getStopValue();
void setIsStop(bool flag=false);
private:
void run();
bool isStop;
signals:
void delDone();
public slots:
};
#endif