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

相关推荐
Data_agent3 分钟前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
leiming65 分钟前
C++ 02 函数模板案例
开发语言·c++·算法
weixin_421585016 分钟前
PYTHON 迭代器1 - PEP-255
开发语言·python
小新11017 分钟前
vs2022+Qt插件初体验,创建带 UI 界面的 Qt 项目
开发语言·qt·ui
摘星编程24 分钟前
Ascend C编程语言详解:打造高效AI算子的利器
c语言·开发语言·人工智能
雨中飘荡的记忆43 分钟前
Java面向对象编程详解
java·开发语言
222you2 小时前
线程的常用方法
java·开发语言
云栖梦泽2 小时前
易语言界面美化与组件扩展
开发语言
catchadmin2 小时前
PHP 值对象实战指南:避免原始类型偏执
android·开发语言·php
Trouville012 小时前
Python中encode和decode的用法详解
开发语言·python