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

相关推荐
ComputerInBook3 分钟前
C++ 标准模板库算法之 transform 用法
开发语言·c++·算法·transform算法
杰哥技术分享10 分钟前
PHP Yii2 安装SQL Server扩展-MAC M4 Pro芯片
开发语言·php
快下雨了L38 分钟前
Lua现学现卖
开发语言·lua
香饽饽~、2 小时前
【第十一篇】SpringBoot缓存技术
java·开发语言·spring boot·后端·缓存·intellij-idea
Devil枫3 小时前
Kotlin扩展函数与属性
开发语言·python·kotlin
菠萝加点糖3 小时前
Kotlin Data包含ByteArray类型
android·开发语言·kotlin
2301_803554524 小时前
c++中类的前置声明
java·开发语言·c++
不想写bug呀7 小时前
多线程案例——单例模式
java·开发语言·单例模式
我不会写代码njdjnssj7 小时前
网络编程 TCP UDP
java·开发语言·jvm
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python