1.新建一个MyThread类,创建好以后修改继承关系,继承于QThread;
2.直接使用QThread类中的虚函数run()
(这是子线程处理函数,在这种方法中有且只有一个子线程处理函数!,注意使用时不能直接调用,要通过start()
间接调用),在MyThread类中对其进行重写即可。
代码如下:
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QWidget>
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
protected:
//QThread类的虚函数
//线程处理函数
//不能直接调用,通过start()间接调用
virtual void run();
signals:
void isDone();
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
//QThread-->F1-->Protected Functions-->virtual void run()
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
//很复杂的数据处理,需要耗时5s
sleep(5);
qDebug()<<"子线程号:"<<QThread::currentThread();
emit isDone();//处理完后发送信号
}
mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QTimer>
#include"mythread.h"
#include<QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class MyWidget; }
QT_END_NAMESPACE
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr);
~MyWidget();
void dealTimeout();//自定义的定时器槽函数
void dealDone();//自定义的线程结束槽函数
void stopThread();//自定义的线程停止槽函数
private slots:
void on_pushButton_clicked();
private:
Ui::MyWidget *ui;
QTimer *myTimer;
MyThread *thread;//子线程对象
};
#endif // MYWIDGET_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);
qDebug()<<"主线程号:"<<QThread::currentThread();
myTimer=new QTimer(this);
//只要定时器启动,自动触发timeout()
connect(myTimer,&QTimer::timeout,this,&MyWidget::dealTimeout);
//分配空间
thread=new MyThread(this);
//线程处理完后,会发射isDone()信号函数,触发该信号后使用自定义的槽函数去处理
connect(thread,&MyThread::isDone,this,&MyWidget::dealDone);
//当按下窗口右上角x时,窗口会自动触发destroyed()信号函数
connect(this,&MyWidget::destroyed,this,&MyWidget::stopThread);
}
void MyWidget::dealDone()
{
qDebug()<<"it is over!";
myTimer->stop();//关闭定时器
}
void MyWidget::stopThread()
{
//停止线程
thread->quit();
//等待线程处理完手头动作
thread->wait();
}
MyWidget::~MyWidget()
{
delete ui;
}
void MyWidget::dealTimeout()
{
static int i=0;
i++;
ui->lcdNumber->display(i);
}
void MyWidget::on_pushButton_clicked()
{
if(myTimer->isActive()==false)
{
myTimer->start(100);
}
#if 0
//模拟非常复杂的数据处理,耗时较长
QThread::sleep(5);//void QThread::sleep(unsigned long secs)//Forces the current thread to sleep for secs seconds.
#endif
//启动线程,处理数据
thread->start();
}