問題是QTimer.singleShot()
未返回對QTimer
的引用。無論如何,我不知道獲得定時器ID,所以你可以使用這種方法殺死它。但是,您可以將一個正常的QTimer
實例化並使其成爲單次計時器(這不是您提供的代碼中所做的操作,在QTimer
的實例上調用singleShot
會創建一個您無權訪問的新QTimer
。 )
但是,一切都不會丟失。您可以創建一個正常的QTimer
並使用setSingleShot(True)
將其轉換爲單次計時器。如果你想中止定時器,這允許你調用stop()
方法。請參閱下面的代碼示例,在3秒的超時時間內完成您所需的操作。您可以快速連續按下按鈕多次,並在停止後3秒鐘打印一次「hello」。如果你推一次,等待4秒鐘,然後再次推,它當然會打印兩次!
希望有幫助!
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyApp(QWidget):
def __init__(self,*args,**kwargs):
QWidget.__init__(self,*args,**kwargs)
self.current_timer = None
self.layout = QVBoxLayout(self)
self.button = QPushButton('start timer')
self.button.clicked.connect(self.start_timer)
self.layout.addWidget(self.button)
def start_timer(self):
if self.current_timer:
self.current_timer.stop()
self.current_timer.deleteLater()
self.current_timer = QTimer()
self.current_timer.timeout.connect(self.print_hello)
self.current_timer.setSingleShot(True)
self.current_timer.start(3000)
def print_hello(self):
print 'hello'
# Create QApplication and QWidget
qapp = QApplication(sys.argv)
app = MyApp()
app.show()
qapp.exec_()
是否有必要創建第二個'QTimer'如果已經存在一個? –
@BedingedFingers謝謝!相應地編輯說明...可以請看看它是否更有意義? – gravetii
現在它更混亂了,早些時候更好。 ;) –