正文
界面
头文件
#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication5.h"
#include <QThread>
class WorkerThread : public QThread
{
Q_OBJECT
// 重写 run 函数,用于执行耗时操作
void run() override {
int val = 0;
while (val < 100)
{
++val;
emit resultReady(val);
msleep(50);
}
}
signals:
// 声明 resultReady 信号,用于通知 UI 线程
void resultReady(int val);
};
class QtGuiApplication5 : public QMainWindow
{
Q_OBJECT
public:
QtGuiApplication5(QWidget *parent = Q_NULLPTR);
private:
Ui::QtGuiApplication5Class ui;
private slots:
// 第一个槽,用于接收按钮点击信号,开启非 UI 线程执行耗时操作
void StartWorkInAThread();
// 第二个槽,用于接收非 UI 线程中的通知信号,然后更新 UI
void HandleResults(int val);
};
源文件
#include "QtGuiApplication5.h"
QtGuiApplication5::QtGuiApplication5(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(StartWorkInAThread()));
}
void QtGuiApplication5::StartWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread();
// 连接非 UI 线程中的信号和 UI 线程中的槽
connect(workerThread, SIGNAL(resultReady(int)), this, SLOT(HandleResults(int)));
connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
workerThread->start();
}
void QtGuiApplication5::HandleResults(int val)
{
ui.progressBar->setValue(val);
}
参考
一去丶二三里 - 《Qt 之 QThread(深入理解)》