在Qt中有两种使用定时器的方法,一种方法是使用QObject类的定时器;另一种方法是使用QTimer类。 QObect类的定时器通过调用QObject.startTimer(),可以启动一个参数以毫秒为时间单位间隔的定时器,这个函数返回一个唯一的整数定时器的标识符。该定时器开始就会在每一个时间间隔"触发",直到明确的使用这个定时器的标识符来调用QObject.killTimer()来结束它。当定时器触发时,应用程序会发送一个QTimerEvent()事件。在Qt事件循环中,处理器按照事件队列的顺序来处理定时器事件。如果处理器正忙于其它事件处理时,定时器就不能被立即处理。 startTimer的格式为: int QObject.startTimer (self, int interval[,Qt.TimerType timerType = Qt.CoarseTimer])
它启动一个定时器并返回该定时器的ID, 如果未能成功启动定时器,将返回0。定时器启动后,直到调用killTimer()删除该定时器前,每隔interval毫秒时间间隔将触发一次超时事件。如果interval为0,那么定时器事件在没有窗口系统事件需要处理时都会触发。参数timerType的类型为枚举类型Qt.TimerType,它包含三个可用值: - Qt.PreciseTimer (0):精确定时器:尽可能保持毫秒准确;
- Qt.CoarseTimer (1): 低精度定时器:5%的误差间隔;
- Qt.VeryCoarseTimer(2): 特低精度定时器:只能到秒级。
timerEvent的格式为: timerEvent(self,QTimerEvent qEvent)
通过QTimerEvent的timerId()可以取得定时器的ID。 killTimer的格式为: killTimer(self,int id)
中止通过startTimer获得的id定时器。 测试QObject的定时器功能在窗口中创建一个显示当前时间的时钟,点击'启动'按钮后,开始显示时间,点击'停止'按钮,终止时间更新。完整代码如下: import sys,time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLCDNumber, QVBoxLayout)
class DemoObjectTimer(QWidget):
def __init__(self, parent=None):
super(DemoObjectTimer, self).__init__(parent)
# 设置窗口标题
self.setWindowTitle('实战PyQt5: QObject定时器 演示!')
# 设置窗口大小
self.resize(400, 200)
self.initUi()
def initUi(self):
self.timer_id = 0
self.btnStart = QPushButton('启动')
self.btnStart.setMinimumHeight(48)
self.btnStart.clicked.connect(self.onButtonStartClicked)
self.start = False
self.lcd = QLCDNumber(self)
#设置液晶显示的最低高度
self.lcd.setMinimumHeight(100)
#设置数字位数
self.lcd.setDigitCount(8)
#设置数字显示模式, 十进制
self.lcd.setMode(QLCDNumber.Dec)
#设置数字屏显示样式
self.lcd.setSegmentStyle(QLCDNumber.Flat)
#设置外观样式
self.lcd.setStyleSheet("border: 2px solid black; color: red; background: blue;")
vLayout = QVBoxLayout(self)
vLayout.addWidget(self.lcd)
vLayout.addStretch()
vLayout.addWidget(self.btnStart)
self.setLayout(vLayout)
def onButtonStartClicked(self):
if self.start:
self.start = False
self.btnStart.setText('启动')
if(self.timer_id):
self.killTimer(self.timer_id)
self.timer_id = 0
self.lcd.display('0')
else:
self.start = True
self.btnStart.setText('停止')
self.timer_id = self.startTimer(1000, Qt.VeryCoarseTimer)
def timerEvent(self, event):
self.lcd.display(time.strftime('%H:%M:%S'))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = DemoObjectTimer()
window.show()
sys.exit(app.exec())
运行效果如下图: 测试QObject类的定时器 使用QTimerQTimer类提供了重复和单次触发信号的定时器。QTimer类为定时器提供了一个高级别的编程接口。 很容易使用QTimer:首先创建一个QTimer,连接timeout()信号到适当的槽函数,并调用start(),然后在恒定的时间间隔会发射timeout()信号。 注意:当QTimer的父对象被销毁时,它也会被自动销毁。 QTimer的常用方法有: - setInterval(self,int msec): 定时器触发的时间间隔毫秒数。如果interval为0,那么定时器事件在没有窗口系统事件需要处理时都会发生。
- startTimer(self.[int msec]): 启动定时器。
- stop(self): 停止定时器。
- isActive(self): 如果定时器在运行,返回True,否则,返回False。
- timerId(self): 如果定时器在运行,返回定时器的ID,否则,返回-1。
- interval(self): 返回setInterval()的设定值。
- setSingleShot(self,bool asingleShot) 如果为True,定时器只工作一次;否则重复工作。
- setTimerType(self,Qt.TimerType timerType): 指定定时器的类型,参数可参照QObject.startTimer()。
- timerType(): 返回setTimerType()的设定值。
可以通过设置setSingleShot(true)来让定时器只执行一次。也可以使用静态函数QTimer.singleShot()。如: QTimer.singleShot(200, self.updateTimer);
QTimer发出的信号: - timeout():定时器超时后,这个信号被发射。这是一个私有的信号。它可以在信号连接使用,但不能由用户发出。
测试QTimer使用QTimer实现上面的测试例子,完整代码如下: import sys,time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLCDNumber, QVBoxLayout)
class DemoTimer(QWidget):
def __init__(self, parent=None):
super(DemoTimer, self).__init__(parent)
# 设置窗口标题
self.setWindowTitle('实战PyQt5: QTimer定时器 演示')
# 设置窗口大小
self.resize(400, 200)
self.initUi()
def initUi(self):
self.timer = QTimer(self)
self.timer.timeout.connect(self.onTimeOut)
self.btnStart = QPushButton('启动')
self.btnStart.setMinimumHeight(48)
self.btnStart.clicked.connect(self.onButtonStartClicked)
self.start = False
self.lcd = QLCDNumber(self)
#设置液晶显示的最低高度
self.lcd.setMinimumHeight(100)
#设置数字位数
self.lcd.setDigitCount(8)
#设置数字显示模式, 十进制
self.lcd.setMode(QLCDNumber.Dec)
#设置数字屏显示样式
self.lcd.setSegmentStyle(QLCDNumber.Flat)
#设置外观样式
self.lcd.setStyleSheet("border: 2px solid black; color: red; background: blue;")
vLayout = QVBoxLayout(self)
vLayout.addWidget(self.lcd)
vLayout.addStretch()
vLayout.addWidget(self.btnStart)
self.setLayout(vLayout)
def onButtonStartClicked(self):
if self.start:
self.start = False
self.btnStart.setText('启动')
self.timer.stop()
self.lcd.display('0')
else:
self.start = True
self.btnStart.setText('停止')
self.timer.start(1000)
def onTimeOut(self):
self.lcd.display(time.strftime('%H:%M:%S'))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = DemoTimer()
window.show()
sys.exit(app.exec())
运行结果如下图: 测试QTimer定时器 本文知识点- 使用QObject类的定时器功能;
- QTimerEvent定时器事件;
- 使用QTimer定时器;
- QTimer.singleShot()单次定时器。
喜欢本文内容就关注, 收藏,点赞,评论和转发。
|