问题是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
现在它更混乱了,早些时候更好。 ;) –