QThread Class▲
-
Header: QThread
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Inherits: QObject
-
Inherited By:
-
Group: QThread is part of thread
Detailed Description▲
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 &
amp;parameter) {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals
:
void
resultReady(const
QString &
amp;result);
}
;
class
Controller : public
QObject
{
Q_OBJECT
QThread workerThread;
public
:
Controller() {
Worker *
worker =
new
Worker;
worker-&
gt;moveToThread(&
amp;workerThread);
connect(&
amp;workerThread, &
amp;QThread::
finished, worker, &
amp;QObject::
deleteLater);
connect(this
, &
amp;Controller::
operate, worker, &
amp;Worker::
doWork);
connect(worker, &
amp;Worker::
resultReady, this
, &
amp;Controller::
handleResults);
workerThread.start();
}
~
Controller() {
workerThread.quit();
workerThread.wait();
}
public
slots:
void
handleResults(const
QString &
amp;);
signals
:
void
operate(const
QString &
amp;);
}
;
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() override
{
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals
:
void
resultReady(const
QString &
amp;s);
}
;
void
MyObject::
startWorkInAThread()
{
WorkerThread *
workerThread