PyQt5 QTimer count until specific seconds

南笙酒味 提交于 2020-03-03 05:19:03

问题


I am creating a program in python and i am using pyqt. I am currently working with the QTimer and i want to print "timer works" every seconds and stop printing after 5 seconds. Here is my code:

timers = []
def thread_func():
    print("Thread works")
    timer = QtCore.QTimer()
    timer.timeout.connect(timer_func)
    timer.start(1000)
    print(timer.remainingTime())
    print(timer.isActive())
    timers.append(timer)

def timer_func():
    print("Timer works")

回答1:


Below is a simple demo showing how to create a timer that stops after a fixed number of timeouts.

from PyQt5 import QtCore

def start_timer(slot, count=1, interval=1000):
    counter = 0
    def handler():
        nonlocal counter
        counter += 1
        slot(counter)
        if counter >= count:
            timer.stop()
            timer.deleteLater()
    timer = QtCore.QTimer()
    timer.timeout.connect(handler)
    timer.start(interval)

def timer_func(count):
    print('Timer:', count)
    if count >= 5:
        QtCore.QCoreApplication.quit()

app = QtCore.QCoreApplication([])
start_timer(timer_func, 5)
app.exec_()


来源:https://stackoverflow.com/questions/46656634/pyqt5-qtimer-count-until-specific-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!