信号
信号是用于界面自动变化的一个工具,原理是信号绑定了一个函数,当信号被触发时函数即被调用
举个例子
from PyQt5 import QtWidgets,QtCore from untitled import Ui_Form import time class MyWindow(QtWidgets.QWidget,Ui_Form): _signal=QtCore.pyqtSignal(str) #定义信号,定义参数为str类型 def __init__(self): super(MyWindow,self).__init__() self.setupUi(self) self.myButton.clicked.connect(self.myPrint)# 按下按钮执行myPrint self._signal.connect(self.mySignal) #将信号连接到函数mySignal def myPrint(self): self.tb.setText("") self.tb.append("正在打印,请稍候") self._signal.emit("打印结束了吗")# 信号被触发 def mySignal(self,string): print(string) self.tb.append("打印结束") if __name__=="__main__": # 以下代码作用为展现ui界面 import sys app=QtWidgets.QApplication(sys.argv) myshow=MyWindow() myshow.show() sys.exit(app.exec_())
定时器
定时器的作用是让某个函数定时的启动,原理是创建一个QTimer对象,将其timeout信号连接到相应的槽(绑定函数名),并调用start(),定时器会以恒定的间隔发出timeout信号,直到调用stop()。
举个例子:秒表功能(每隔一秒刷新界面,直到按下停止按钮)
from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys from datetime import datetime class WinTimer(QWidget): def __init__(self,parent=None): super(WinTimer,self).__init__(parent) ###界面显示 self.label_start=QLabel("开始时间:") self.label_curr=QLabel("当前时间:") self.label_total=QLabel("时间总计:") self.startBtn=QPushButton("开始") self.endBtn=QPushButton("停止") self.endBtn.setEnabled(False) ##时间变量 self.start_time=QDateTime.currentDateTime() self.stop_time = QDateTime.currentDateTime() ###定时器 self.timer=QTimer() self.timer.timeout.connect(self.currTime) layout=QGridLayout() layout.addWidget(self.label_start,0,0,1,2) layout.addWidget(self.label_curr, 1,0,1,2) layout.addWidget(self.label_total, 2,0,1,2) layout.addWidget(self.startBtn, 3, 0) layout.addWidget(self.endBtn, 3, 1) self.setLayout(layout) self.startBtn.clicked.connect(self.startTimer) self.endBtn.clicked.connect(self.endTimer) self.setWindowTitle("QTimer") self.resize(250,100) def currTime(self): self.stop_time=QDateTime.currentDateTime() str_time = self.stop_time.toString("yyyy-MM-dd hh:mm:ss dddd") self.label_curr.setText("当前时间:"+str_time) str_start = self.start_time.toString("yyyy-MM-dd hh:mm:ss") str_curr = self.stop_time.toString("yyyy-MM-dd hh:mm:ss") startTime = datetime.strptime(str_start, "%Y-%m-%d %H:%M:%S") endTime = datetime.strptime(str_curr, "%Y-%m-%d %H:%M:%S") seconds = (endTime - startTime).seconds self.label_total.setText("时间总计:" + str(seconds)+"s") def startTimer(self): self.start_time = QDateTime.currentDateTime() str_time = self.start_time.toString("yyyy-MM-dd hh:mm:ss dddd") self.label_start.setText("开始时间:" + str_time) self.timer.start(1000) self.startBtn.setEnabled(False) self.endBtn.setEnabled(True) def endTimer(self): self.timer.stop() self.startBtn.setEnabled(True) self.endBtn.setEnabled(False) if __name__=="__main__": app=QApplication(sys.argv) form=WinTimer() form.show()