方法
自定义一个继承QThread的类Thread,重载QThread中的run()函数,在run()函数中写入需要执行的工作;
调用start()函数来启动线程,调用start函数时,会自动调用run函数。
运行效果
代码示例
thread.h文件
#ifndef THRAED1_H
#define THRAED1_H
#include <QThread>
class Thread : public QThread
{
Q_OBJECT
public:
explicit Thread(QObject *parent = nullptr);
static Thread* GetInst()
{
static Thread hw;
return &hw;
}
void reSetExit() {
m_bIsExitThread = !m_bIsExitThread; }
void reSetStop() {
m_bIsStopThread = !m_bIsStopThread; }
signals:
void sigValue(int value);
protected:
void run() override;
private:
bool m_bIsExitThread = true; //退出线程
bool m_bIsStopThread = false; //暂停线程
int fValue = 0;
};
#endif // THRAED1_H
thread.cpp文件
#include "thread.h"
#include<QDebug>
Thread::Thread(QObject *parent) : QThread(parent)
{
}
void Thread::run()
{
fValue = 0;
while(true)
{
if(isInterruptionRequested())
break;
if(m_bIsStopThread)
continue;
if(m_bIsExitThread)
break;
fValue++;
emit sigValue(fValue);
msleep(50);
}
}
widget.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "thread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_btnStart_clicked();
void on_btnStop_clicked();
private:
Ui::Widget *ui;
Thread *my_thread = nullptr;
};
#endif // WIDGET_H
widget.cpp文件
#include "widget.h"
#include "ui_widget.h"
#include<QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
my_thread = Thread::GetInst();
//线程退出信号
connect(my_thread, &Thread::finished, [&]{
qDebug()<<"finished...";
ui->textEdit->append("finished");
});
//线程int值变化信号
connect(my_thread, &Thread::sigValue, this, [&](int value){
QString str = QString(QStringLiteral("线程输出:%1")).arg(value);
ui->textEdit->append(str);
});
}
Widget::~Widget()
{
//my_thread->quit();
//退出线程
my_thread->wait();
delete ui;
}
void Widget::on_btnStart_clicked()
{
if(my_thread->isRunning())
{
ui->btnStart->setText(QStringLiteral("启动"));
my_thread->reSetExit();
}
else
{
ui->btnStart->setText(QStringLiteral("退出"));
my_thread->reSetExit();
my_thread->start();
}
}
void Widget::on_btnStop_clicked()
{
static bool bIsStop = true;
my_thread->reSetStop();
if(bIsStop)
{
ui->btnStop->setText(QStringLiteral("继续"));
bIsStop = false;
}
else
{
ui->btnStop->setText(QStringLiteral("暂停"));
bIsStop = true;
}
}
Widget UI布局