The thread class in PyQt, which inherits the QThread class when used.
The thread that starts the interface is tentatively called the UI thread. The interface executes commands in its own UI thread.
If time-consuming operations such as network connections and database operations are performed in the UI thread, the interface will get stuck and a "not responding" warning may appear on Windows.
Blocking UI threads degrades user experience and application stability. So we can put time-consuming operations in threads to execute them.
QThread represents a thread, and we can override the run function to perform the action we want.
QThread can be used to interact with the interface and transfer data.
PyQt4 QThread Code Example
•Python2.7 # -*- coding: utf-8 -*- import sys from PyQt4 import QtCore from import QCoreApplication from import QWidget, QPushButton, QApplication, QTextBrowser class TimeThread(): signal_time = (str, int) # Signal def __init__(self, parent=None): super(TimeThread, self).__init__(parent) = True = 0 def start_timer(self): = 0 () def run(self): while : print "Working", () self.signal_time.emit("Running time:", ) # Send a signal += 1 (1) class TimeDialog(QWidget): def __init__(self): super(TimeDialog, self).__init__() self.timer_tv = QTextBrowser(self) self.init_ui() self.timer_t = TimeThread() self.timer_t.signal_time.connect(self.update_timer_tv) def init_ui(self): (300, 200) ('TimeDialog') self.timer_tv.setText("Wait") self.timer_tv.setGeometry((10, 145, 198, 26)) self.timer_tv.move(0, 15) btn1 = QPushButton('Quit', self) ('Click to quit') (()) (200, 150) (().quit) start_btn = QPushButton('Start', self) start_btn.setToolTip("Click to start") start_btn.move(50, 150) (start_btn, ("clicked()"), self.click_start_btn) def click_start_btn(self): self.timer_t.start_timer() def update_timer_tv(self, text, number): self.timer_tv.setText((text + " " + str(number))) if __name__ == '__main__': app = QApplication() time_dialog = TimeDialog() time_dialog.show() (app.exec_())
Signals used in QThread signal_time = (str, int) specifies the arguments str and int
Send Signal self.signal_time.emit("Running time:", )
External receive signal self.timer_t.signal_time.connect(self.update_timer_tv)
The signal is connected to the method update_timer_tv(self, text, number), note that the signal and the method arguments should correspond to each other.
We can define many different signals in use
To start a thread, call start()