Evgenij LegotskojNov. 25, 2019, 5:53 p.m.

PyQt5 - Tutorial 009. Using QThread with MoveToThread

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

Content

ADS

Introduction

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.

Program

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.setObjectName("Form")
        Form.resize(453, 408)
        self.verticalLayout = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.textBrowser = QtWidgets.QTextBrowser(Form)
        self.textBrowser.setObjectName("textBrowser")
        self.verticalLayout_2.addWidget(self.textBrowser)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    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
            self.newTextAndColor.emit(
                '{} - thread 2 variant 1.\n'.format(str(time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()))),
                QColor(0, 0, 255)
            )
            QtCore.QThread.msleep(1000)

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


class MyWindow(QtWidgets.QWidget):

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

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

    @QtCore.pyqtSlot(str, object)
    def addNewTextAndColor(self, string, color):
        self.ui.textBrowser.setTextColor(color)
        self.ui.textBrowser.append(string)

    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()
    window.show()
    sys.exit(app.exec())

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
c

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

b

простите за беспокойсто. Разобрался )) Спасибо Вам огромное. По сути у Вас тольько и разобрался с сигналами и слотами

b

в продолжение, хотелось бы уточнить такой вопрос. Испускаемые сигналы - они глобальны? то есть на сгенерированный pyqtSignal в классе А, можно ли "подписаться" в классах B,C,D своими слотами? То есть по одному сигналу, может ли каждый класс выполнять что-то свое?

Да, можно. к одному сигналу можно быть подключено какое угодно количество слотов в каком угодно наборе объектов.

b

спасибо Вам большое

YA

Hello. Let's say I want to send some variables to "run" define. How can we do that? I modified your code, I tried something like below, but the GUI is frozen that way. I could not be able to understand it. Can you please give me some advice?

import sys
import time
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QPushButton, QListWidget, QVBoxLayout, QLineEdit
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QObject
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer

class RequestHandler(QObject):
    running = False
    output_signal = pyqtSignal(list)

    @pyqtSlot(str, int)
    def run(self, ip, port, unit):
        client = ModbusClient(ip, port=port, framer=ModbusRtuFramer)
        client.connect()
        print("run")
        while True:
            print(int(QThread.currentThreadId()))

            for i in range(2):
                try:
                    m = client.read_holding_registers(0,9, unit = unit[i])
                    self.output_signal.emit(m.registers)
                except:
                    self.output_signal.emit(["ERROR"])

            QThread.msleep(2000)

class MyWindow(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super().__init__()
        self.list1 = QLineEdit()
        self.buton = QPushButton("BASlAT")
        self.v = QVBoxLayout()
        self.v.addWidget(self.list1)
        self.v.addWidget(self.buton)
        self.buton.clicked.connect(self.start)
        self.setLayout(self.v)
        self.show()

    @pyqtSlot(list)
    def addNewTextAndColor(self, output):
        print(output)

        pass

    def start(self):
        unit = [14, 15]
        self.thread = QThread()
        self.browserHandler = RequestHandler()
        self.browserHandler.moveToThread(self.thread)
        print(int(self.thread.currentThreadId()))
        self.browserHandler.output_signal.connect(self.addNewTextAndColor)
        self.thread.started.connect(self.browserHandler.run("192.168.1.100", 502, unit))
        self.thread.start()


app = QtWidgets.QApplication(sys.argv)
window = MyWindow()

sys.exit(app.exec())

c

Здравствуйте.
Разрешите пару вопросов...
1. Зачем нужен running = False ?
2. Можно ли (нужно?) принудительно завершать поток?
Ещё раз спасибо огромное! Ваш ресурс пожалуй лучший по Qt и PyQt на русском (и не только) языке!

День добрый

  1. Не нужен, случайно осталось при подготовке материала
  2. Можно, нужно, не обязательно - зависит от логики вашей программы
b

А можете, пожалуйста, уточнить каким образом можно принудительно завершить поток?

Вызвать либо метод quit() либо эквивалентный его вариант - метод exit(0)

b

Спасибо большое

Comments

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

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
y

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
n

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
s

C++ - Тест 003. Условия и циклы

  • Result:42points,
  • Rating points-8
Popular publications in the last 90 Days
Last comments
f
  • fryn3
  • Oct. 21, 2021, 5:24 a.m.

QML - Tutorial 038. Using the clip property to crop child objects inside Item or Rectangle

Зачем внутри OpacityMask Item, почему сразу Rectangle не вставить? И что за rect.adapt? Мое предложение: layer.enabled: true layer.effect: OpacityMask { …
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Добрый вечер, на "лету" не работает, только перезапуск
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Спасибо, завтра опробую и отпишусь по результату

Django - Tutorial 007. Adding Pagination based on django-bootstrap3

Просто список каких-нибудь объектов передавайте, который дёрнули ищ api стороннего сервера from django.core.paginator import Paginatorobjects = ['john', 'paul', 'george', 'ringo']p = Pagina…
b

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Спасибо большое
Now discuss on the forum
  • grig_p
  • Oct. 21, 2021, 8:33 a.m.

Применение стилей *.qss к собственным виджетам.

Здравствуйте! Я бы хотел в виджете использовать некоторые свои свойства для его элементов. Задаю в коде виджета так: Q_PROPERTY(QColor sig1_color READ sig1Color WRITE setSig1Col…
j
  • juvf
  • Oct. 21, 2021, 7:31 a.m.

Qt Quick Virtual Keyboard

В QtCreator есть пример на QML с виртуальной клавиатурой "Qt Quick Virtual Keyboard - Basic Example". Собрал, работает. Собрал свой хеловорд свою программу состоящую из главного окна …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
  • Nomad
  • Oct. 15, 2021, 6:39 a.m.

Вопрос из раздела "как реализовать"

Всем привет. Есть бизнес логика которую надо реализовать на джанге, она состоит в следующем: надо реализовать функционал регистрации/авторизации компаний у которого есть свой дашборд …

Проблема с созданием файлов перевода для составного проекта

Я имею ввиду, если у вас был старые ts файлы, то написать парсер, который составил бы словарь переводов. Например. "Hello world" - "Привет мир" "Hello dev" - "Привет dev" и…
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB