//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

 

//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);