[Qt] Create thread program example

00. Table of Contents

Article Directory

01. Overview

Multi-threaded programming can effectively solve the problem of performing a time-consuming operation without freezing the user interface of an application. Thread-related content can be viewed in the help through the " Thread Support in Qt"keywords.

02. Development environment

Windows system : Windows10

Qt version : Qt5.15 or Qt6

03. Create thread class subclass

mythread.h file

#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 file

#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. Main window and program

Main interface design

Insert picture description here

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. Program execution results

"子线程: 0"
"子线程: 1"
"子线程: 2"
"子线程: 3"
"子线程: 4"
"子线程: 5"

06. Appendix

6.1 Summary of Qt tutorials
URL: https://dengjin.blog.csdn.net/article/details/115174639

6.2 Program download
Download: 2Thread.rar