💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 概述 1. 继承 QThread 类重写了 run() 函数 2. 执行完成后发出一个完成信号 3. connect 处理 QThread::finished() 信号触发 QThread::deleteLater() ``` connect(thread, &WorkerThread::finished, thread, &WorkerThread::deleteLater); ``` 4. 通过从run()函数直接或者间接地调用 QThread::exec(),可以让线程进入事件循环 ``` while (true) { //...code exec(); } ``` ## 示例 ``` class WorkerThread : public QThread { Q_OBJECT public: WorkerThread(QObject *parent = 0) : QThread(parent) { } protected: void run() { for (int i = 0; i < 1000000000; i++); emit done(); } signals: void done(); }; // main.cpp ... // 在GUI 中显示计时器 QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, [=]() { static int sec = 0; lcdNumber->display(QString::number(sec++)); }); WorkerThread *thread = new WorkerThread(this); // 子线程处理完发出信号 connect(thread, &WorkerThread::done, timer, &QTimer::stop); // 子线程完成后,删除子线程 connect(thread, &WorkerThread::finished, thread, &WorkerThread::deleteLater); // 点击事件触发信号 connect(button, &QPushButton::clicked, [=]() { timer->start(1); thread->start(); }); ```