问题
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