要实现多线程,我们要先继承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_())