PyQt5中QTimer的使用

2022-10-20 08:38:27

一般来说,应用都是单线程的,但单线程有一些缺点,例如,有一个线程比较耗时,像有些算法执行起来时间较长,程序就会出现卡顿,此时用户就有可能关闭这个程序。解决这个问题的方法就涉及到了多线程。其中计时器模块QTimer一个计时器模块就设计到多线程技术。

关于QTimer的使用,我们一开始要创建一个QTimer的实例,将timeout信号连接到相应的槽,再调用start()。定时器就会以设定好的间隔发出timeout信号,当窗口控件收到这个信号后,就会停止计时器。

方法描述
start(毫秒)启动或重新启动定时器,时间间隔为毫秒,若定时器已经运行,就会停止重新启动
stop()停止计时器
信号描述
singleShot在给定的时间间隔后调用一个槽函数发射此信号
timeout当定时器超时时发射此信号
import sysfrom PyQt5.QtWidgetsimport*from PyQt5.QtCoreimport*classTime(QWidget):def__init__(self):super(Time, self).__init__()
        self.setWindowTitle("动态显示时间")

        self.label= QLabel("当前时间")
        self.start= QPushButton("Start")
        self.end= QPushButton("End")

        layout= QGridLayout()

        self.timer= QTimer()
        self.timer.timeout.connect(self.showTime)

        layout.addWidget(self.label,0,0,1,2)
        layout.addWidget(self.start,1,0)
        layout.addWidget(self.end,1,1)

        self.start.clicked.connect(self.startTimer)
        self.end.clicked.connect(self.endTimer)

        self.setLayout(layout)defshowTime(self):
        time= QDateTime.currentDateTime()
        timeDisplay= time.toString("yyyy-MM-dd hh:mm:ss dddd")
        self.label.setText(timeDisplay)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)
    main= Time()
    main.show()
    sys.exit(app.exec_())

效果如图

在这里插入图片描述

若我们想设置一个提醒窗口,该窗口在设定时间内自动关闭,下面的代码给出了一个示例:

from PyQt5.QtWidgetsimport*from PyQt5.QtCoreimport*if __name__=="__main__":
    app= QApplication(sys.argv)
    label= QLabel('<font color=blue size=127><b>Hello PyQt5 3秒后自动关闭!</b></font>')# 设置为无边框窗口
    label.setWindowFlags(Qt.SplashScreen| Qt.FramelessWindowHint)
    label.show()# 设置10秒后自动退出
    QTimer.singleShot(3000, app.quit)

    sys.exit(app.exec_())

效果如图:

在这里插入图片描述

  • 作者:百里不守约_45690024
  • 原文链接:https://blog.csdn.net/qq_45690024/article/details/104563041
    更新时间:2022-10-20 08:38:27