QT工作线程更新界面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//mainwindow.h
 
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
#include <QThread>
 
namespace Ui {
class MainWindow;
}
 
class WorkerThread : public QThread
{
    Q_OBJECT
 
    // 在工作线程中定义一个信号,用于发送更新界面的请求
signals:
    void updateUI(const QString& text);
 
protected:
    void run() override {
        // 模拟耗时操作
        for(int i = 0; i < 5; i++) {
            sleep(1);
            // 在工作线程中发送更新界面的请求
            emit updateUI(QString("Iteration %1").arg(i+1));
        }
    }
};
 
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 updateUI(const QString& text);
 
private:
    Ui::MainWindow *ui;
    WorkerThread *workerThread;
 
};
#endif // MAINWINDOW_H

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//mainwindow.cpp
 
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    workerThread = new WorkerThread();
 
    // 在主线程中连接工作线程的信号和主线程的槽函数
    connect(workerThread, &WorkerThread::updateUI, this, &MainWindow::updateUI);
 
    workerThread->start();
 
}
 
void MainWindow::updateUI(const QString& text) {
    ui->label->setText(text);
}
 
 
MainWindow::~MainWindow()
{
    delete ui;
}

  

 Qt 5之后,可以使用新的语法来代替SIGNAL和SLOT宏。新的语法是使用函数指针来指定信号和槽函数,而不再需要宏

connect(sender, &Sender::signal, receiver, &Receiver::slot);
 
posted @   ahuo  阅读(119)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示