QT开启多线程,首先想到的是QThread类,重写run方法;通过start方法执行run函数。
具体步骤:
1、新建MyThread类,继承自QThread;
2、重载QThread类的run方法;
3、在需要使用多线程的地方,实例化MyThread类,并调用start方法;
demo
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL0YDO0IzNyIjM1EzNwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
1、新建myThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
class MyThread :public QThread
{
Q_OBJECT
public:
MyThread();
void closeThread();
protected:
void run() override;
private:
bool isStop;
signals:
void signal_thread_value(int value);
};
#endif // MYTHREAD_H
2、新建myThread.cpp
#include <mythread.h>
MyThread::MyThread()
{
isStop = false;
}
void MyThread::closeThread()
{
isStop = true;
}
void MyThread::run()
{
int index = 0;
while (!isStop) {
qDebug() << ++index;
msleep(1000);
}
}
3、修改mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <mythread.h>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_btn_start_thread_clicked();
void on_btn_close_thread_clicked();
void myThreadFinished();
private:
Ui::MainWindow *ui;
MyThread* myThread;
};
#endif // MAINWINDOW_H
4、修改mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("Thread专题");
myThread = new MyThread;
connect(myThread, SIGNAL(finished()), this, SLOT(myThreadFinished()));
}
MainWindow::~MainWindow()
{
delete ui;
}
/**
* @brief MainWindow::on_btn_start_thread_clicked
* 启动函数
*/
void MainWindow::on_btn_start_thread_clicked()
{
myThread->start();
}
/**
* @brief MainWindow::on_btn_close_thread_clicked
* 关闭线程
*/
void MainWindow::on_btn_close_thread_clicked()
{
myThread->closeThread();
myThread->wait();
}
/**
* @brief MainWindow::myThreadFinished
* 线程结束
*/
void MainWindow::myThreadFinished()
{
qDebug() << "线程执行结束";
}
5、实现效果
6、将线程计算结果打印在屏幕上
在myThread.h中增加信号,并在run方法中触发该信号;在主界面中接收该信号,并在槽函数中将接收到的值设置到label中: