我怎样才能在PyQt4中杀掉一次QtCore.QTimer?

gra*_*tii 5 python timer pyqt pyqt4 python-2.7

因此,在我的应用程序中,我创建一个单独的QtCore.QTimer对象,然后调用singleShot它上面的方法,在60秒后调用一个函数.现在,在任何给定的时间点,如果我需要再次调用singleShot它上面的方法并阻止前一个singleShot方法生效(这阻止它调用传递给它的调用者,如果第二次singleShot调用它之前前60秒),我需要做什么?我如何"杀死"前一个QTimer并完全忘记它并且只能使用当前的工作QTimer

有人可以帮我解决这个问题吗?

这里只是一个示例代码:

def main():
    q = QtCore.QTimer()
    q.singleShot(4000, print_hello)
    q.killTimer(id)     ##how can I get the value of 'id' so that print_hello() is not called before the end of the 4 seconds?

def print_hello():
    print 'hello'
Run Code Online (Sandbox Code Playgroud)

谢谢

thr*_*les 12

问题是QTimer.singleShot()不返回对引用的引用QTimer.无论如何我都不知道获取Timer ID所以你可以使用该方法杀死它.但是,您可以实例化一个法线QTimer并使其成为单次计时器(这不是您在提供的代码中所做的,调用创建一个您无权访问的singleShot实例.)QTimer QTimer

但是,一切都不会丢失.您可以使用创建法线QTimer并将其转换为单次计时器setSingleShot(True).stop()如果您希望中止计时器,则允许您调用该方法.请参阅下面的代码示例,它会在3秒超时时执行您所需的操作.您可以快速连续按下按钮多次,并在停止后3秒打印"你好".如果你按一次,等待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_()
Run Code Online (Sandbox Code Playgroud)