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

相关推荐
z人间防沉迷k1 分钟前
堆(Heap)
开发语言·数据结构·笔记·python·算法
不二狗11 分钟前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
炯哈哈19 分钟前
【上位机——WPF】Window标签常用属性
开发语言·c#·wpf·上位机
小白学大数据25 分钟前
Python爬虫如何应对网站的反爬加密策略?
开发语言·爬虫·python
Akiiiira26 分钟前
【数据结构】队列
java·开发语言·数据结构
程序媛学姐31 分钟前
Java级联操作:CascadeType的选择与最佳实践
java·开发语言
LetsonH1 小时前
Python工具链UV整合环境管理
开发语言·python·uv
zm2 小时前
UDP 多点通信
开发语言·php
.小墨迹2 小时前
Apollo学习——planning模块(3)之planning_base
linux·开发语言·c++·学习·自动驾驶
小喵喵生气气2 小时前
Python60日基础学习打卡D26
开发语言·python