python - 如何在 PyQt4 中杀死单发 QtCore.QTimer?

标签 python python-2.7 timer pyqt pyqt4

因此,在我的应用程序中,我创建了一个单一的 QtCore.QTimer 对象,然后在它上面调用 singleShot 方法以在 60 秒后调用一个函数。现在,在任何给定的时间点,如果我需要再次对其调用 singleShot 方法并阻止先前的 singleShot 方法生效(即阻止它调用传递给它的调用者,如果在第一个 60 秒之前第二次调用 singleShot,我需要做什么?我怎样才能“杀死”以前的 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'

谢谢

最佳答案

问题是 QTimer.singleShot() 没有返回对 QTimer 的引用。我不知道如何获取计时器 ID,因此您可以使用该方法将其终止。但是,您可以实例化一个普通的 QTimer 并使其成为单次计时器(这不是您在提供的代码中所做的,在 singleShot 的实例上调用 QTimer 创建一个您无权访问的 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_()

关于python - 如何在 PyQt4 中杀死单发 QtCore.QTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21079941/

相关文章:

python - XBee API Python 库中缺少超时

python - 如何在 Python 中为 argparse 设置自定义输出处理程序?

mysql - mysql 查询语法错误以在 python 中更新

python - 如何测试字符串包含列表中的元素并通过 Pandas 将目标元素分配给另一列

javascript - 如何在jQuery中传递和设置 slider 图像显示时间?

python - 安装 Pygame 后 pygame.init() 显示为 undefined variable

python - 在 python 列表中查找最大值和索引?

python - 有没有更快的 bin 文件到 numpy 数组的方法?

c# - 如何使用时间间隔在 Windows 窗体中的照片之间切换?

c++ - timer_create() : -1 EAGAIN (Resource temporarily unavailable)