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

相关推荐
妮妮喔妮2 分钟前
【无标题】
开发语言·前端·javascript
fie88897 分钟前
浅谈几种js设计模式
开发语言·javascript·设计模式
喝可乐的布偶猫14 分钟前
Java类变量(静态变量)
java·开发语言·jvm
喝可乐的布偶猫1 小时前
韩顺平之第九章综合练习-----------房屋出租管理系统
java·开发语言·ide·eclipse
江山如画,佳人北望1 小时前
C#程序入门
开发语言·windows·c#
牵牛老人1 小时前
Qt处理USB摄像头开发说明与QtMultimedia与V4L2融合应用
stm32·单片机·qt
coding随想2 小时前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
念九_ysl3 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
yaoxin5211233 小时前
124. Java 泛型 - 有界类型参数
java·开发语言
liulilittle3 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信