【Qt多线程】计算数字的平方和

1. 多线程介绍

在程序开发中,为了解决耗时和操作堵塞等问题,一般将耗时的操作(如算法处理、数据通信)放在子线程中处理。

Qt提供了多线程的类:QThread

常用函数:

// QThread 类常用 API
// 构造函数
QThread::QThread(QObject *parent = Q_NULLPTR);
// 判断线程中的任务是不是处理完毕了
bool QThread::isFinished() const;
// 判断子线程是不是在执行任务
bool QThread::isRunning() const;

// Qt中的线程可以设置优先级
Priority QThread::priority() const;
void QThread::setPriority(Priority priority);
优先级:
    QThread::IdlePriority        --> 最低的优先级
    QThread::LowestPriority
    QThread::LowPriority
    QThread::NormalPriority
    QThread::HighPriority
    QThread::HighestPriority
    QThread::TimeCriticalPriority
    QThread::InheritPriority    --> 最高的优先级, 默认是这个

// 退出线程, 停止底层的事件循环
// 退出线程的工作函数
void QThread::exit(int returnCode = 0);
// 调用线程退出函数之后, 线程不会马上退出因为当前任务有可能还没有完成, 用这个函数是
// 等待任务完成, 然后退出线程, 一般情况下会在 exit() 后边调用这个函数
bool QThread::wait(unsigned long time = ULONG_MAX);

下面就用重写run函数的方法来实现多线程,子线程做数据处理,主线程用来调用。

2. 示例程序

首先在ui文件中创建一个Label和一个Button:

在这里插入图片描述

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class MyThread : public QThread
{
    
    
    Q_OBJECT

public:
    MyThread(QObject *parent = nullptr);

protected:
    void run() override;

signals:
    void resultReady(int result);
};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"

MyThread::MyThread(QObject *parent)
    : QThread(parent)
{
    
    
}

void MyThread::run()
{
    
    
    int sum = 0;
    for (int i = 0; i <= 100; ++i) {
    
    
        sum += i * i;
    }
    emit resultReady(sum);
}

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 handleResult(int result);

    void on_btn_clicked();

private:
    Ui::MainWindow *ui;
    MyThread *m_thread;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);

    m_thread = new MyThread(this);
    connect(m_thread, &MyThread::resultReady, this, &MainWindow::handleResult);
}

MainWindow::~MainWindow()
{
    
    
    delete ui;
}

void MainWindow::handleResult(int result)
{
    
    
    ui->resultLabel->setText(QString::number(result));
}

void MainWindow::on_btn_clicked()
{
    
    
    m_thread->start();
}

运行结果如下:

在这里插入图片描述

3. Qt学习路线

今天顺便在chatgpt问了一下Qt的学习路线,如下:

在这里插入图片描述

以上。

猜你喜欢

转载自blog.csdn.net/qq_40344790/article/details/129772879