mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QThread> #include <QDebug> #include <QPushButton> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class WorkerThread; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; /* 在 MainWindow 类里声明对象 */ WorkerThread *workerThread; /* 声明一个按钮,使用此按钮点击后开启线程 */ QPushButton *pushButton; private slots: /* 槽函数,用于接收线程发送的信号 */ void handleResults(const QString &result); /* 点击按钮开启线程 */ void pushButtonClicked(); }; /* 新建一个 WorkerThread 类继承于 QThread */ class WorkerThread : public QThread { /* 用到信号槽即需要此宏定义 */ Q_OBJECT public: WorkerThread(QWidget *parent = nullptr) { Q_UNUSED(parent); } /* 重写 run 方法,继承 QThread 的类,只有 run 方法是在新的线程里 */ void run() override { QString result = "线程开启成功"; /* 这里写上比较耗时的操作 */ // ... // 延时 2s,把延时 2s 当作耗时操作 sleep(2); /* 发送结果准备好的信号 */ emit resultReady(result); } signals: /* 声明一个信号,译结果准确好的信号 */ void resultReady(const QString &s); }; #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); /* 设置位置与大小 */ this->setGeometry(0, 0, 800, 480); /* 对象实例化 */ pushButton = new QPushButton(this); workerThread = new WorkerThread(this); /* 按钮设置大小与文本 */ pushButton->resize(100, 40); pushButton->setText("开启线程"); /* 信号槽连接 */ connect(workerThread, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString))); connect(pushButton, SIGNAL(clicked()), this, SLOT(pushButtonClicked())); } MainWindow::~MainWindow() { /* 进程退出,注意本例 run()方法没写循环,此方法需要有循环才生效 */ workerThread->quit(); /* 阻塞等待 2000ms 检查一次进程是否已经退出 */ if (workerThread->wait(2000)) { qDebug()<<"线程已经结束!"<<endl; } delete ui; } void MainWindow::handleResults(const QString &result) { /* 打印出线程发送过来的结果 */ qDebug()<<result<<endl; } void MainWindow::pushButtonClicked() { /* 检查线程是否在运行,如果没有则开始运行 */ if (!workerThread->isRunning()) workerThread->start(); }
mainwindow.h
mainwindow.cpp