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

相关推荐
m0_736919105 小时前
C++代码风格检查工具
开发语言·c++·算法
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖6 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472466 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ7 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024067 小时前
C++ 文件和流
开发语言
m0_706653237 小时前
分布式系统安全通信
开发语言·c++·算法
寻寻觅觅☆8 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
杨了个杨89828 小时前
memcached部署
qt·websocket·memcached
lightqjx8 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列