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
6
class
MyObject
:
public
QObject
7
{
8
Q_OBJECT
9
void
startWorkInAThread();
10
private
slots
:
11
void
handleResults
(){};
12
};
13
14
//! [reimpl-run]
15
class
WorkerThread
:
public
QThread
16
{
17
Q_OBJECT
18
public
:
19
explicit
WorkerThread
(
QObject
*
parent
=
nullptr
) :
QThread
(
parent
) { }
20
protected
:
21
void
run
()
override
{
22
QString
result
;
23
/* ... here is the expensive or blocking operation ... */
24
emit
resultReady
(
result
);
25
}
26
signals
:
27
void
resultReady
(
const
QString
&
s
);
28
};
29
30
void
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]
41
class
Worker
:
public
QObject
42
{
43
Q_OBJECT
44
45
public
slots
:
46
void
doWork
(
const
QString
&
parameter
) {
47
QString
result
;
48
/* ... here is the expensive or blocking operation ... */
49
emit
resultReady
(
result
);
50
}
51
52
signals
:
53
void
resultReady
(
const
QString
&
result
);
54
};
55
56
class
Controller
:
public
QObject
57
{
58
Q_OBJECT
59
QThread
workerThread
;
60
public
:
61
Controller
() {
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
}
69
~
Controller
() {
70
workerThread.quit();
71
workerThread.wait();
72
}
73
public
slots
:
74
void
handleResults
(
const
QString
&);
75
signals
:
76
void
operate
(
const
QString
&);
77
};
78
//! [worker]
79
80
void
Controller
::handleResults(
const
QString &) { }
Controller
Definition
src_corelib_thread_qthread.cpp:57
Controller::~Controller
~Controller()
Definition
src_corelib_thread_qthread.cpp:69
Controller::Controller
Controller()
Definition
src_corelib_thread_qthread.cpp:61
MyObject
[8]
Definition
src_corelib_kernel_qobject.cpp:113
WorkerThread
[reimpl-run]
Definition
src_corelib_thread_qthread.cpp:16
Worker
[reimpl-run]
Definition
src_corelib_thread_qthread.cpp:42
qtbase
src
corelib
doc
snippets
code
src_corelib_thread_qthread.cpp
Generated on
for Qt by
1.14.0