movthread

The QThread class provides a platform-independent way to manage threads.

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

You can use worker objects by moving them to the thread using QObject::moveToThread().

class Worker : public QObject

{

Q_OBJECT

public slots:

void doWork(const QString &parameter) {

QString result;

/* ... here is the expensive or blocking operation ... */

emit resultReady(result);

}

signals:

void resultReady(const QString &result);

};

class Controller : public QObject

{

Q_OBJECT

QThread workerThread;

public:

Controller() {

Worker *worker = new Worker;

worker->moveToThread(&workerThread);

connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);

connect(this, &Controller::operate, worker, &Worker::doWork);

connect(worker, &Worker::resultReady, this, &Controller::handleResults);

workerThread.start();

}

~Controller() {

workerThread.quit();

workerThread.wait();

}

public slots:

void handleResults(const QString &);

signals:

void operate(const QString &);

};

The code inside the Worker's slot would then execute in a separate thread. However, you are free to connect the Worker's slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.

Another way to make code run in a separate thread, is to subclass QThread and reimplement run(). For example:

class WorkerThread : public QThread

{

Q_OBJECT

void run() Q_DECL_OVERRIDE {

QString result;

/* ... here is the expensive or blocking operation ... */

emit resultReady(result);

}

signals:

void resultReady(const QString &s);

};

void MyObject::startWorkInAThread()

{

WorkerThread *workerThread = new WorkerThread(this);

connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);

connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);

workerThread->start();

相关推荐
掘金安东尼7 小时前
Transformers.js:让大模型跑进浏览器
开发语言·javascript·ecmascript
im_AMBER7 小时前
React 05
开发语言·前端·javascript·笔记·学习·react.js·前端框架
迷失的walker7 小时前
【Qt C++ QSerialPort】QSerialPort fQSerialPortInfo::availablePorts() 执行报错问题解决方案
数据库·c++·qt
B站计算机毕业设计之家7 小时前
计算机视觉:pyqt5+yoloV5目标检测平台 python实战 torch 目标识别 大数据项目 目标跟踪(建议收藏)✅
深度学习·qt·opencv·yolo·目标检测·计算机视觉·1024程序员节
conkl7 小时前
在 CentOS 系统上实现定时执行 Python 邮件发送任务完整指南
linux·运维·开发语言·python·centos·mail·邮箱
whycthe8 小时前
c++竞赛常用函数
java·开发语言
wydaicls8 小时前
了解一下kernel6.12中cpu_util_cfs_boost函数的逻辑
linux·开发语言
Violet_YSWY8 小时前
final是干嘛的
java·开发语言
一只小透明啊啊啊啊9 小时前
Java的中间件
java·开发语言·中间件
学编程就要猛9 小时前
数据结构初阶:Java中的ArrayList
java·开发语言·数据结构