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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】