PyQt5-定时器QTimer

2022/5/22 23:05:37

本文主要是介绍PyQt5-定时器QTimer,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

PyQt5中的定时器类是QTimer。QTimer不是一个可见的界面组件,在UI Designer的组件面板里找不到它。

QTimer主要的属性是interval,是定时中断的周期,单位是毫秒。

QTimer主要的信号是timeout(),在定时中断时发射此信号,若要在定时中断里做出响应,就需要编写与timeout()信号关联的槽函数。

image

下图是我设计的界面

image

image

窗体UI文件Widget.ui在UI Designer里可视化设计,界面上组件的布局和属性设置见源文件。窗体业务逻辑类QmyWidget的完整代码如下:

import sys
from PyQt5.QtWidgets import  QWidget,QApplication
from PyQt5.QtCore import QTime,QTimer

from ui_QtApp import Ui_Form
class QmyWidget(QWidget):
    def __init__(self,parent=None):
        super().__init__(parent) #调用父类构造函数
        self.ui=Ui_Form() #创建UI对象
        self.ui.setupUi(self) #构造UI
        self.timer=QTimer()  #创建定时器
        self.timer.stop() #停止
        self.timer.setInterval(1000) #定时周期1000ms
        self.timer.timeout.connect(self.do_timer_timeout)
        self.counter=QTime() #创建计时器

    ## ====由connectSlotsByName()自动与组件的信号关联的槽函数=====
    def on_pushButton_clicked(self): #开始按钮
        self.timer.start()#开始定时
        self.counter.start() #开始计时
        self.ui.pushButton.setEnabled(False)
        self.ui.pushButton_2.setEnabled(True)
        self.ui.pushButton_3.setEnabled(False)

    def on_pushButton_3_clicked(self): #设置定时器的周期
        self.timer.setInterval(self.ui.spinBox.value())

    def on_pushButton_2_clicked(self): #停止按钮
        self.timer.stop() #定时器停止
        tmMs=self.counter.elapsed() #计时器经过的毫秒数
        ms=tmMs %1000 #取余数,毫秒
        sec=tmMs/1000 #整秒
        timeStr="经过的时间:%d秒,%d毫秒"%(sec,ms)
        self.ui.label.setText(timeStr)
        self.ui.pushButton.setEnabled(True)
        self.ui.pushButton_2.setEnabled(False)
        self.ui.pushButton_3.setEnabled(True)

    ## =======自定义槽函数=======
    def do_timer_timeout(self): #定时中断相应
        curTime=QTime.currentTime() #获取当前时间
        self.ui.lcdNumber.display(curTime.hour())
        self.ui.lcdNumber_2.display(curTime.minute())
        self.ui.lcdNumber_3.display(curTime.second())

if __name__ == "__main__": ##用于当前窗体测试
    app=QApplication(sys.argv) #创建GUI应用程序
    form=QmyWidget() #创建窗体
    form.show()
    sys.exit(app.exec_())

应用程序主程序appMain.py文件如下:

## GUI应用程序主程序
import sys
from PyQt5.QtWidgets import  QApplication
from myWidget import  QmyWidget

app = QApplication(sys.argv) # 创建app,用QApplication类
myWidget = QmyWidget() #创建窗体
myWidget.show()
sys.exit(app.exec_())

程序中几个过程的代码功能分析如下。

(1)构造函数功能在构造函数中创建了定时器对象self.timer并立刻停止。设置定时周期为1000ms,并为其timeout()信号关联了自定义槽函数do_timer_timeout()。

还创建了一个计时器对象self.counter,这是一个QTime类的实例,用于在开始与停止之间计算经过的时间。

(2)定时器开始运行

点击“开始”按钮后,定时器开始运行,计时器也开始运行。

定时器的定时周期到了之后发射timeout()信号,触发关联的自定义槽函数do_timer_timeout()执行,此槽函数的功能通过类函数QTime.currentTime()读取当前时间,然后将时、分、秒显示在三个LCD组件上。

(3)定时器停止运行

点击“停止”按钮时,定时器停止运行。计时器通过调用elapsed()函数可以获得上次执行start()之后经过的毫秒数。

最终效果如下:

image



这篇关于PyQt5-定时器QTimer的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程