python - 停止 QTimer.singleShot() 计时器

标签 python python-2.7 pyqt pyqt4 qtimer

  1. 是否可以停止QTimer.singleShot()计时器? (请不要告诉 我使用 QTimer 对象的 stop() 函数 - 我真的很想 知道静态函数 QTimer.singleShot() 是否可以在之前停止 时间已过)

  2. 如果在第二个 QTimer.singleShot() 之前启动,会发生什么情况? 第一个已经过去了?是第一个被杀,还是第二个被杀 而是开始了?

最佳答案

Q. What happens if a second QTimer.singleShot() is launched before the first one has elapsed? Is the first one killed or is a second one started instead?

  • 所有计时器都是独立工作的,因此如果连续启动两个计时器,两个计时器都会运行直至完成。

Q. Is it possible to stop a QTimer.singleShot() timer? (Please don't tell me to use the stop() function of a QTimer object - I really want to know if the static function QTimer.singleShot() can be stopped before its time has elapsed)

  • 静态函数创建一个处理计时器的内部对象,因此没有可用的公共(public) API 来停止它。然而,有一个涉及 QAbstractEventDispatcher 的 hack 可以解决这个限制。它依赖于实现细节,因此不建议在生产代码中使用它。但你问这是否可能,所以这里有一个演示:

    from PyQt4 import QtCore, QtGui
    
    class Window(QtGui.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.button = QtGui.QPushButton('Start', self)
            self.button.clicked.connect(self.handleTimer)
            self.edit = QtGui.QLineEdit(self)
            self.edit.setReadOnly(True)
            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.button)
            layout.addWidget(self.edit)
            self._timer = None
    
        def handleTimer(self):
            dispatcher = QtCore.QAbstractEventDispatcher.instance()
            if self._timer is None:
                self.edit.clear()
                self.button.setText('Stop')
                QtCore.QTimer.singleShot(3000, self.handleTimeout)
                self._timer = dispatcher.children()[-1]
            else:
                dispatcher = QtCore.QAbstractEventDispatcher.instance()
                dispatcher.unregisterTimers(self._timer)
                self.button.setText('Start')
                self._timer = None
    
        def handleTimeout(self):
            self._timer = None
            self.button.setText('Start')
            self.edit.setText('timeout')
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 150, 300, 100)
        window.show()
        sys.exit(app.exec_())
    

关于python - 停止 QTimer.singleShot() 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309833/

相关文章:

python - 没有 PYTHONPATH 时的 PYTHONPATH 是什么?

python - 在运行时替换 python Mixin 类

Python pandas 合并 keyerror

python - 如何在 PyQt 中使用 QThreads 双向设置信号和槽?

python - 尝试将图像分成多个文件夹来训练和测试文件夹,但代码仅读取/复制最后一个文件夹

python - 将函数列表应用于值的名称?

python - 如何洗牌并将大列表拆分为较小的列表,以最大限度地提高速度?

python - 不计算以 float 为底的对数

python - PyQt5 QListView拖放创建新的隐藏项

python - pyqt5中的多个窗口