PyQt5中使用QTimer定时刷新:当要执行可能会超过设定时间的代码

有时候,我们需要定时对数据进行刷新,以获取到最新的数据,然后对数据进行处理, 这时候可以采用PyQT5 中的QTimer 类。但是,有时我们并不知道这段代码会执行多长的时间,有时候会超过我们设定的刷新的时间,如 self.timer.start(1000)是1 秒的话,或者是我们不知道代码执行多久。这是我遇到的一个小问题,下面我们开始解决这个问题,其实也很简单,特此记录一下,希望能帮助到其他的朋友们。


定义QTimer 类

self.timer = QTimer(self)
self.timer.start(1000) #单位为毫秒
self.stop()

 QTimer 类的信号

self.timer.timeout.connect(self.function)    #到达设定的时间后,执行function函数
self.timer.singleShot.connect(1000, app.quit) #设置 1 秒后界面自动关闭

 全部的代码:

主要是在长时间的代码函数中,前后增加:

self.timer.stop()
.........
.........
self.timer.start()

start() 切记不要加任何的参数

from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QGridLayout, QLabel
from PyQt5.QtCore import QTimer
import sys


class WinForm(QWidget):

    def __init__(self, parent=None):
        super(WinForm, self).__init__(parent)

        self.setWindowTitle("QTimer demo")
        self.label = QLabel('测试')
        self.startBtn = QPushButton('开始')
        self.endBtn = QPushButton('结束')

        layout = QGridLayout(self)

        # 初始化一个定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.myFunction) #到达设定的时间后,执行槽函数代码

        layout.addWidget(self.label, 0, 0, 1, 2)
        layout.addWidget(self.startBtn, 1, 0)
        layout.addWidget(self.endBtn, 1, 1)

        # 连接按键操作和槽函数
        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.endTimer)

        self.setLayout(layout)

    def startTimer(self):
        self.timer.start(5000) # 5000 单位是毫秒, 即 5 秒
        self.label.setText('开始执行了-----')
    
    def endTimer(self):   
        self.timer.stop()
    
    def myFunction(self):
#         for i in range(10):
#             self.label.setText(str(i) + ',')
        #如果执行该代码的时间远远超过 5 秒的话: 使用下面的方法
        self.timer.stop()
        for i in range(100000000): #此代码远远超过 5 秒
            if i % 100 == 0:
                print(i)
        self.label.setText('这是很长的代码')
        self.timer.start() #此时, start 中不要加任何的时间
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = WinForm()
    form.show()
    sys.exit(app.exec_())

 

posted @ 2020-04-23 15:51  蜘蛛侠不会飞  阅读(2579)  评论(0编辑  收藏  举报

俺的博客

https://blog.csdn.net/qq_40587575

俺的公众号