methodologies
The QThread class in PyQt is used to implement multi-threaded utilization, and the pyqtSignal class in PyQt is used to implement triggering and capturing of messages, i.e., defining events and subscribing to events
Ways to implement multithreading with the QThread class
1, create a new python class, inherited from QThread
from import QThread class SubThread(QThread):
2. Rewrite the __init__(), __del__() and run() functions.
from import QThread class SubThread(QThread): def __init__(self): super().__init__() # Add the required code below def __del__(self): () def run(self): # The following code is added for sub-thread execution
3, will be inherited from the QThread class instantiation, and then call the instance object of the start () function, you can start a new thread
[Emphasis added]
Instances of subclasses of QThread must be placed between the app = () and (app.exec_()) code。
if __name__ == '__main__': app = () subthread = SubThread() () (app.exec_())
Implementing message triggering and capturing with the pyqtSignal class
1, atIn-class header definition of the pyqtSignal propertyRemember, it'sClass Level Attributes
from import QThread, pyqtSignal class SubThread(QThread): messagetrigger = pyqtSignal(str) def __init__(self): super().__init__() # Add the required code below def __del__(self): () def run(self): # The following code is added for sub-thread execution
2, use where you need to trigger a message, call pyqtSignal's emit() function to trigger the message
import timefrom import QThread, pyqtSignal, QObject class SubThread(QThread): messagetrigger = pyqtSignal(str) def __init__(self): super().__init__() def __del__(self): () def run(self): ('Subthread started') (2) ('End of subthread')
3, capture the message, use pyqtSignal's connect() to connect to the callback function, and process the captured message within the callback function, the complete code is as follows:
import sysimport timefrom import QThread, pyqtSignal, QObject from PyQt5 import QtWidgets class SubThread(QThread): messagetrigger = pyqtSignal(str) def __init__(self): super().__init__() def __del__(self): () def run(self): ('Subthread started') (2) ('End of subthread') def callback(msg): print(msg) if __name__ == '__main__': app = () subthread = SubThread() (callback) () (app.exec_())
Above is python to realize multi-threading and inter-thread communication simple method of details, more information about python multi-threading inter-thread communication please pay attention to my other related articles!