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

相关推荐
phltxy6 分钟前
解锁JavaScript WebAPI:从基础到实战,打造交互式网页
开发语言·javascript
资生算法程序员_畅想家_剑魔7 分钟前
Java常见技术分享-分布式篇-分布式系统基础理论
java·开发语言·分布式
千疑千寻~13 分钟前
【Qt图形】详细介绍Qt中的图形场景、图元、视图
qt
千疑千寻~39 分钟前
【Qt图形】Qt中的图形场景、图元、视图 的坐标的转换
qt
FL162386312942 分钟前
C# winform部署yolo26-obb旋转框检测的onnx模型演示源码+模型+说明
开发语言·c#
大猫和小黄1 小时前
Java异常处理:从基础到SpringBoot实战解析
java·开发语言·spring boot·异常
半夏知半秋1 小时前
kcp学习-通用的kcp lua绑定
服务器·开发语言·笔记·后端·学习
csbysj20201 小时前
并查集路径压缩
开发语言
JavaEdge.2 小时前
java.io.IOException: Previous writer likely failed to write hdfs报错解决方案
java·开发语言·hdfs
C+++Python2 小时前
C++类型判断
开发语言·c++