2017-10-09 213 views
1

我正在python中創建一個程序,我正在使用pyqt。我目前正在使用QTimer,我想每秒打印一次「定時器工作」並在5秒後停止打印。這裏是我的代碼:PyQt5 QTimer計數,直到特定的秒

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") 
+0

'QTimer'類不支持在固定數量的超時後停止。你必須保持計數並明確地停止它。 – ekhumoro

+0

你能爲我做一個演示嗎?我只是一個初學者。 – Jaypee

回答

0

下面是展示如何創建一個固定數量的超時之後停止計時器一個簡單的演示。

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_() 
+0

哇!這是我一直在尋找'。在這裏感謝朋友! – Jaypee

相關問題