00. 目录
01. 概述
多线程编程可以有效解决在不冻结一个应用程序用户界面的情况下执行一个耗时操作的问题。线程相关内容可以在帮助中通过"Thread Support in Qt
"关键字查看。
02. 开发环境
Windows系统:Windows10
Qt版本:Qt5.15或者Qt6
03. 创建线程类子类
mythread.h文件
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QObject>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject *parent = 0);
~MyThread();
void stop();
protected:
void run();
private:
volatile bool stopped;
};
#endif // MYTHREAD_H
mythread.cpp文件
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent):QThread(parent)
{
stopped = false;
}
MyThread::~MyThread()
{
}
void MyThread::stop()
{
stopped = true;
}
void MyThread::run()
{
qreal i = 0;
while(!stopped)
{
qDebug() << QString("子线程: %1").arg(i);
msleep(1000);
i++;
}
stopped = false;
}
04. 主窗口和程序
主界面设计
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include "mythread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
private slots:
//启动线程
void on_pushButton_clicked();
//终止线程
void on_pushButton_2_clicked();
private:
Ui::Dialog *ui;
MyThread thread;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
//启动线程
void Dialog::on_pushButton_clicked()
{
thread.start();
ui->pushButton->setEnabled(false);
ui->pushButton_2->setEnabled(true);
}
//终止线程
void Dialog::on_pushButton_2_clicked()
{
if (thread.isRunning())
{
thread.stop();
ui->pushButton->setEnabled(true);
ui->pushButton_2->setEnabled(false);
}
}
05. 程序执行结果
"子线程: 0"
"子线程: 1"
"子线程: 2"
"子线程: 3"
"子线程: 4"
"子线程: 5"
06. 附录