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

相关推荐
秋田君33 分钟前
Qt_QVariant
开发语言·qt
江华森36 分钟前
Python 实现高德地图找房(三):地图可视化与高德 JS API
开发语言·javascript·python
weixin_4713830341 分钟前
args,...args与Parameters<T>
开发语言·前端
杜子不疼.1 小时前
【Qt初识】工程起步:项目创建、代码解读与对象树
数据库·c++·qt
ctrl_v助手1 小时前
C#表达题笔记
开发语言·c#
2zcode2 小时前
基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
米饭不加菜3 小时前
使用万用表判断三极管(BJT)好坏
java·开发语言
绝世唐门三哥3 小时前
vue3中页面返回时刷新首页的处理方案
开发语言·前端·javascript
nianniannnn3 小时前
c++复习自存--流、异常处理、多线程与C++工程规范
开发语言·c++
geovindu3 小时前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#