要實現多線程,我們要先繼承QThread類並重新實現其中的run()函數,也就是說把耗時的操作放入run()函數中
1 import sys 2 from PyQt5.QtCore import Qt, QThread,pyqtSignal 3 from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout,QHBoxLayout 4 5 6 class Demo(QWidget): 7 def __init__(self): 8 super(Demo, self).__init__() 9 10 self.button = QPushButton('開始', self) 11 self.button.clicked.connect(self.count_func) 12 self.button_2 = QPushButton('停止', self) 13 self.button_2.clicked.connect(self.stop_count_func) 14 15 self.label = QLabel('0', self) 16 self.label.setAlignment(Qt.AlignCenter) 17 18 self.my_thread = MyThread()#實例化線程對象 19 self.my_thread.my_signal.connect(self.set_label_func) 20 #線程自定義信號連接的槽函數 21 22 self.h_layout = QHBoxLayout() 23 self.v_layout = QVBoxLayout() 24 self.h_layout.addWidget(self.button) 25 self.h_layout.addWidget(self.button_2) 26 self.v_layout.addWidget(self.label) 27 self.v_layout.addLayout(self.h_layout) 28 self.setLayout(self.v_layout) 29 30 31 def stop_count_func(self): 32 self.my_thread.is_on = False 33 self.my_thread.count = 0 34 35 def count_func(self): 36 self.my_thread.is_on = True 37 self.my_thread.start()#啟動線程 38 39 def set_label_func(self, num): 40 self.label.setText(num) 41 #由於自定義信號時自動傳遞一個字符串參數,所以在這個槽函數中要接受一個參數 42 43 44 class MyThread(QThread):#線程類 45 my_signal = pyqtSignal(str) #自定義信號對象。參數str就代表這個信號可以傳一個字符串 46 def __init__(self): 47 super(MyThread, self).__init__() 48 self.count = 0 49 self.is_on = True 50 51 52 def run(self): #線程執行函數 53 while self.is_on : 54 print(self.count) 55 self.count += 1 56 self.my_signal.emit(str(self.count)) #釋放自定義的信號 57 #通過自定義信號把str(self.count)傳遞給槽函數 58 59 self.sleep(1) #本線程睡眠n秒【是QThread函數】 60 61 62 if __name__ == '__main__': 63 app = QApplication(sys.argv) 64 demo = Demo() 65 demo.show() 66 sys.exit(app.exec_())