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

相关推荐
咸鱼求放生8 小时前
Java 8 Stream API
java·开发语言
盒马盒马8 小时前
Rust:Trait 抽象接口 & 特征约束
开发语言·rust
天使街23号8 小时前
go-dongle v1.2.0 发布,新增 SM2 非对称椭圆曲线加密算法支持
开发语言·后端·golang
ThreeYear_s8 小时前
【FPGA+DSP系列】——MATLAB simulink仿真三相桥式全控整流电路
开发语言·matlab·fpga开发
yugi9878388 小时前
MATLAB实现白噪声与色噪声仿真
开发语言·matlab
似水এ᭄往昔8 小时前
【C++】--模板进阶
开发语言·c++
Hi202402179 小时前
为QML程序添加启动Logo:提升用户体验
windows·qt·ui·人机交互·qml·启动logo
yue0089 小时前
C# 求取整数的阶乘
java·开发语言·c#
曹绍华9 小时前
android 线程loop
android·java·开发语言
树在风中摇曳10 小时前
C语言动态内存管理:从基础到进阶的完整解析
c语言·开发语言·算法