PyQt5之QTimer定时器
如果要在应用程序中周期性地进行某项操作,比如周期性地检测主机的CPU值,则需要用到QTimer定时器,QTimer类提供了重复的和单次的定时器。要使用定时器,需要先创建一个QTimer实例,将其timeout信号连接到相应的槽,并调用
start()
。然后定时器会以恒定的间隔发出timeout信号,当窗口控件收到timeout信号后,它就会停止这个定时器。
一、QTimer类中的常用方法
方法 | 描述 |
---|---|
start(milliseconds) | 启动或重新启动定时器,时间间隔为毫秒。如果定时器已经运行,它将被停止并重新启动。如果singleShot信号为真,定时器将仅被激活一次 |
Stop() | 停止定时器 |
二、QTimer类中的常用信号
信号 | 描述 |
---|---|
singleShot | 在给定的时间间隔后调用一个槽函数时发射此信号 |
timeout | 当定时器超时时发射此信号 |
三、QTimer的使用
示例1:
import sysfrom PyQt5import QtCorefrom PyQt5.QtWidgetsimport*from PyQt5.QtGuiimport*from PyQt5.QtCoreimport*classDemo(QWidget):
count=0def__init__(self):super().__init__()
self.setGeometry(100,50,500,400)
self.setWindowTitle('QTimer')
self.list= QListWidget()
self.label= QLabel('显示当前时间')
self.start= QPushButton('开始')
self.end= QPushButton('结束')
layout= QGridLayout()#初始化定时器
self.timer= QTimer(self)
self.timer.timeout.connect(self.showTime)
self.start.clicked.connect(self.startTimer)
self.end.clicked.connect(self.endTimer)
layout.addWidget(self.label,0,0,1,2)
layout.addWidget(self.start,1,0)
layout.addWidget(self.end,1,1)
self.setLayout(layout)defshowTime(self):#获取系统现在的时间
time= QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd')
self.label.setText(time)defstartTimer(self):#设置时间间隔并启动定时器
self.timer.start(1000)
self.start.setEnabled(False)
self.end.setEnabled(True)defendTimer(self):#关闭定时器
self.timer.stop()
self.start.setEnabled(True)
self.end.setEnabled(False)if __name__=="__main__":
app= QApplication(sys.argv)
form= Demo()
form.show()
sys.exit(app.exec_())
运行效果如下:
示例2:
import sysfrom PyQt5import QtCorefrom PyQt5.QtWidgetsimport*from PyQt5.QtGuiimport*from PyQt5.QtCoreimport*if __name__=="__main__":
app= QApplication(sys.argv)
label= QLabel('<font color=blue size=20><b>PyQt5,窗口5秒后消失</b></font>')#无边框窗口
label.setWindowFlags(Qt.SplashScreen|Qt.FramelessWindowHint)
label.show()#设置5秒后自动退出
QTimer.singleShot(5000,app.quit)
sys.exit(app.exec_())
运行效果如下: