PyQt5 - Tutorial 009. Using QThread with MoveToThread

PyQt5, QObject, Qt, moveToThread, QThread

Based on one of the questions on the forum, I wrote an example on using QThread in PyQt5, as well as using the moveToThread method to move the class object of the inherited QObject to another thread.

In this example, a certain algorithm is executed, which returns the text through the signal, as well as the color of the text to the main GUI. This data is added to the QTextBrowser with a color setting.

The program will look as follows


There are two main approaches for using QThread in Qt :

  1. Create a new class that inherits from QThread and override the run method
  2. Create a new class that inherits from QObject , write a run method that will execute some code, and transfer the instance of this class to another thread using the moveToThread method

The first method is recommended to be used only if you really need to override the stream class in order to create special functionality in the stream class. If you need to execute some code in another thread, then for this you need to create a separate class that will be transferred to another thread using the moveToThread method.

Also, I want to note right away that you cannot transfer GUI objects to other threads. Qt programs have two kinds of threads:

  • Main stream. GUI thread
  • Workflows. Worker threads

All GUI objects should create and work only in a GUI thread, while various other algorithms can be executed in worker threads.

I quote the documentation

As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads. A secondary thread is commonly referred to as a "worker thread" because it is used to offload processing work from the main thread.

That is, if, even if something works for you in another thread, it will be only an accident that will sooner or later make itself felt. And your program will stop working. Never pass other GUI objects to other threads.


Now consider the code of our program. Please note that the algorithm of actions will be as follows

  1. We write a class that inherits from QObject and has a run method for executing code in another thread
  2. In the window constructor, create a stream object
  3. In the window constructor, create an object that will be transferred to another thread
  4. Transfer the object to another stream
  5. We connect signals and slots
  6. Run the thread

It is advisable to perform all the initialization of the object and stream in this sequence, if you do not already have sufficient experience.
However, then you would not read this article.
If you swap steps 4 and 5, then you first connect the signals and slots, and then transfer the object to another stream, which will break the signal / slot connection. The application window will stop working. Or the application may just crash.

import sys
import time

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QColor

class Ui_Form(object):
    def setupUi(self, Form):
        Form.resize(453, 408)
        self.verticalLayout = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.textBrowser = QtWidgets.QTextBrowser(Form)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.pushButton = QtWidgets.QPushButton(Form)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)


    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Example"))
        self.pushButton.setText(_translate("Form", "Input"))

# Object, which will be moved to another thread
class BrowserHandler(QtCore.QObject):
    running = False
    newTextAndColor = QtCore.pyqtSignal(str, object)

    # method which will execute algorithm in another thread
    def run(self):
        while True:
            # send signal with new text and color from aonther thread
                '{} - thread 2 variant 1.\n'.format(str(time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()))),
                QColor(0, 0, 255)

            # send signal with new text and color from aonther thread
                '{} - thread 2 variant 2.\n'.format(str(time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()))),
                QColor(255, 0, 0)

class MyWindow(QtWidgets.QWidget):

    def __init__(self, parent=None):
        self.ui = Ui_Form()
        # use button to invoke slot with another text and color

        # create thread
        self.thread = QtCore.QThread()
        # create object which will be moved to another thread
        self.browserHandler = BrowserHandler()
        # move object to another thread
        # after that, we can connect signals from this object to slot in GUI thread
        # connect started signal to run method of object in another thread
        # start thread

    @QtCore.pyqtSlot(str, object)
    def addNewTextAndColor(self, string, color):

    def addAnotherTextAndColor(self):
        self.ui.textBrowser.setTextColor(QColor(0, 255, 0))
        self.ui.textBrowser.append('{} - thread 2 variant 3.\n'.format(str(time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()))))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Огромное спасибо!


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

Jan. 16, 2020, 2:19 a.m.
Dmitrij Korjagin

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Jan. 16, 2020, 2:03 a.m.
Lilija Ziganurova

C++ - Test 005. Structures and Classes

  • Result:50points,
  • Rating points-4
Jan. 13, 2020, 3:59 p.m.

C++ - Test 002. Constants

  • Result:100points,
  • Rating points10
Last comments
Jan. 17, 2020, 1:31 a.m.
Andrej Jankovich

Выглядит как ошибка библиотеки. Расскажите подробно на какой платформе вы собираете проект (MinGW или MSVC) их версии и версии Qt.
Jan. 16, 2020, 11:06 a.m.

Доброго времени суток, не подскажите, что делать в данной ситуации, после того, как я сделал все вышеуказанные инструкции для подключения библиотеки к проекту?
Jan. 14, 2020, 4:33 a.m.
Evgenij Legotskoj

Рекомендую Wt, достаточно мощная вещь. Этот фреймворк может использоваться для написания сайтов на C++, либо можно использовать только отдельный компоненты, например только ORM. Но я не знаю, ка…
Jan. 14, 2020, 4:29 a.m.

Спасибо за инфу. Поиск качественной ORM привел меня только к sqlite_orm, но не подходит из-за необходимости полноценной поддержки c++14. Про framework Wt не слышал, спасибо за наводку.
Jan. 14, 2020, 1:50 a.m.
Evgenij Legotskoj

Вы заблуждаетесь. Любая нормальная ORM позволяет выполнение сырых SQL запросов. А если хорошо разобраться в работе моделей данных в Qt, то не составит труда использовать ORM вместе с Qt, ту же с…
Now discuss on the forum
Jan. 17, 2020, 1:20 a.m.

Александр, доброго дня! Я тоже только учусь и поэтому мой код может быть не совершенен. За отклик большое спасибо.
Jan. 16, 2020, 7:14 p.m.

Oct Products Similiar To Lasix Kamagra Now.Co.Uk Sky Pharmacy Canada [url=]Buy Cialis[/url] Viagra Ricetta Ripetibile
Jan. 16, 2020, 5:05 p.m.
Aleksej Vnukov

в лоадер вроде как нельзя передать значение при загрузке, я не нашел такой возможности, через стек без проблем. если использую лоадер - я передаю в С++ нужные параметры, а потом при загрузке стр…
Jan. 16, 2020, 7:16 a.m.
Aleksej Vnukov

доброго времени, есть приложение для телефона с iOS, интерфейс написан на QML, в котором получаю через FileDialog адрес картинки на устройсве (что-то вроде этого "file:assets-library://asset/as…
Jan. 16, 2020, 6:32 a.m.

Правильно ли я понимаю, что используя MVC, модель будет писаться на c++, а представление и контроллер объединены в qml? Не будет ли возникать тормозов в программе и перегруженности кода в qml из…
© EVILEG 2015-2019
Recommend hosting TIMEWEB