线程可以用来处理一些耗时的操作,而定时可以在耗时的操作中处理一些瞬时操作,比如刷新UI,程序可能略显复杂,主要是因为自从学了信号与槽之后不管写啥控件都习惯用信号与槽传递数据,那种收发式的感觉真的很爽
import sys from PyQt5.QtWidgets import QWidget, QFormLayout, QLineEdit, QVBoxLayout, QApplication,QPushButton from PyQt5.QtCore import pyqtSignal, QTimer class Tm(QWidget): msignal = pyqtSignal(int) ssignal = pyqtSignal(int) def __init__(self,parent=None): super(Tm,self).__init__(parent=parent) self.m = 0 self.s = 0 self.status = False self.msignal.connect(self.setmval) #连接信号与槽 self.ssignal.connect(self.setsval) #连接信号与槽 self.mtimer = QTimer() #创建一个定时器 self.stimer = QTimer() #创建一个定时器 self.stimer.timeout.connect(self.stimerout) #定时器超时触发函数 self.mtimer.timeout.connect(self.mtimerout) #定时器超时触发函数 self.initUI() self.btn.clicked.connect(self.startTimer) def initUI(self): self.mline = QLineEdit() self.mline.setText('0') self.sline = QLineEdit() self.sline.setText('0') self.formLayout = QFormLayout() self.formLayout.addRow('m', self.mline) self.formLayout.addRow('s', self.sline) self.btn = QPushButton('startTimer') self.vbox = QVBoxLayout() self.vbox.addLayout(self.formLayout) self.vbox.addWidget(self.btn) self.setLayout(self.vbox) self.show() def setmval(self, value): self.mline.setText(str(value)) def setsval(self, value): self.sline.setText(str(value)) '''开启定时器并设置超时时间为1000毫秒''' def startTimer(self): self.status = ~self.status #取反 if self.status: self.mtimer.start(1000) self.stimer.start(1000) self.btn.setText('StopTimer') #停止计时器 else: self.mtimer.stop() self.stimer.stop() self.btn.setText('StartTimer') #开启计时器 def mtimerout(self): self.m += 1 self.msignal.emit(self.m) def stimerout(self): self.s +=1 self.ssignal.emit(self.s) if __name__ == "__main__": app = QApplication(sys.argv) ex = Tm() sys.exit(app.exec_())效果: