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

相关推荐
CHANG_THE_WORLD39 分钟前
python 批量终止进程exe
开发语言·python
古城小栈41 分钟前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
Gary Studio2 小时前
安卓HAL C++基础-智能指针
开发语言·c++
啧不应该啊2 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
cen__y3 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
xingpanvip3 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
guygg883 小时前
基于遗传算法的双层规划模型求解MATLAB实现
开发语言·matlab
凯瑟琳.奥古斯特3 小时前
SQLAlchemy核心功能解析
开发语言·python·flask
卷Java4 小时前
GPTQ vs AWQ vs GGUF:模型量化工具横向测评
开发语言·windows·python
charlie1145141914 小时前
嵌入式C++工程实践第20篇:GPIO 输入模式内部电路 —— 芯片是如何“听“到外部信号的
开发语言·c++·stm32·单片机