Starting Threads with QThread

A QThread instance represents a thread and provides the means to start() a thread, which will then execute the reimplementation of QThread::run(). The run() implementation is for a thread what the main() entry point is for the application. All code executed in a call stack that starts in the run() function is executed by the new thread, and the thread finishes when the function returns. QThread emits signals to indicate that the thread started or finished executing.

Creating a Thread

To create a thread, subclass QThread and reimplement its run() function. For example:

class MyThread : public QThread
{
    Q_OBJECT

protected:
    void run();
};

void MyThread::run()
{
    ...
}

Starting a Thread

Then, create an instance of the thread object and call QThread::start(). Note that you must create the QApplication (or QCoreApplication) object before you can create a QThread.

The function will return immediately and the main thread will continue. The code that appears in the run() reimplementation will then be executed in a separate thread.

Creating threads is explained in more detail in the QThread documentation.

Note that QCoreApplication::exec() must always be called from the main thread (the thread that executes main()), not from a QThread. In GUI applications, the main thread is also called the GUI thread because it's the only thread that is allowed to perform GUI-related operations.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.