import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
sec = 0
class WorkThread(QThread):
def __init__(self, parent=None):
super(WorkThread, self).__init__(parent)
self.timer = pyqtSignal() # 每隔1秒发送一次信号
self.end1 = pyqtSignal() # 计数完成后发送一次信号
# timer = pyqtSignal() # 每隔1秒发送一次信号
# end1 = pyqtSignal() # 计数完成后发送一次信号
def run(self):
while True:
self.sleep(1) # 休眠1秒
if sec == 5:
self.end1.emit() # 发送end信号
break
self.timer.emit() # 发送timer信号
class Counter(QWidget):
def __init__(self, parent=None):
super(Counter, self).__init__(parent)
self.setWindowTitle("使用线程类(QThread)编写计数器")
self.resize(300, 120)
layout = QVBoxLayout()
self.lcdNumber = QLCDNumber()
layout.addWidget(self.lcdNumber)
button = QPushButton('开始计数')
layout.addWidget(button)
self.workThread = WorkThread()
self.workThread.timer.connect(self.countTime)
self.workThread.end1.connect(self.end1)
button.clicked.connect(self.work)
self.setLayout(layout)
def countTime(self):
global sec
sec += 1
self.lcdNumber.display(sec)
def end1(self):
QMessageBox.information(self,'消息','计数结束',QMessageBox.Ok)
def work(self):
self.workThread.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Counter()
form.show()
sys.exit(app.exec_())
老师:为什么我这里不可以把timer 和 end1定义成实例变量?运行报下面的错误:
Traceback (most recent call last):
File “C:/Users/u243216/Desktop/GUI/multithread/Counter.py”, line 83, in
form = Counter()
File “C:/Users/u243216/Desktop/GUI/multithread/Counter.py”, line 63, in init
self.workThread.timer.connect(self.countTime)
AttributeError: ‘PyQt5.QtCore.pyqtSignal’ object has no attribute ‘connect’
我这个代码只能把timer和end1定义成类变量,在实例方法run中通过访问实例变量的形式(self.timer/self.end1)的方式来访问类变量才可以运行正常。是不是和pyqt5的实现机制有关?