Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_corelib_thread_qthread.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4#include <QtCore/QThread>
5
6class MyObject : public QObject
7{
8 Q_OBJECT
9 void startWorkInAThread();
10private slots:
11 void handleResults(){};
12};
13
14//! [reimpl-run]
15class WorkerThread : public QThread
16{
18public:
19 explicit WorkerThread(QObject *parent = nullptr) : QThread(parent) { }
20protected:
21 void run() override {
23 /* ... here is the expensive or blocking operation ... */
25 }
27 void resultReady(const QString &s);
28};
29
30void MyObject::startWorkInAThread()
31{
32 WorkerThread *workerThread = new WorkerThread(this);
33 connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
34 connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
35 workerThread->start();
36}
37//! [reimpl-run]
38
39
40//! [worker]
41class Worker : public QObject
42{
44
45public slots:
46 void doWork(const QString &parameter) {
48 /* ... here is the expensive or blocking operation ... */
50 }
51
54};
55
56class Controller : public QObject
57{
58 Q_OBJECT
59 QThread workerThread;
60public:
62 Worker *worker = new Worker;
63 worker->moveToThread(&workerThread);
64 connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
65 connect(this, &Controller::operate, worker, &Worker::doWork);
66 connect(worker, &Worker::resultReady, this, &Controller::handleResults);
67 workerThread.start();
68 }
70 workerThread.quit();
71 workerThread.wait();
72 }
73public slots:
74 void handleResults(const QString &);
76 void operate(const QString &);
77};
78//! [worker]
79
80void Controller::handleResults(const QString &) { }