停止QTimer.singleShot()计时器

问题描述:

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

  2. 会发生什么,如果第二QTimer.singleShot()在 第一个已经过去之前启动?是第一个遇难,还是第二个开始改为 ?

+0

您是[海尔特Vancompernolle](http://www.riverbankcomputing.com/pipermail/pyqt/20​​09-February/ 022023.html),我声称我的€5。 – ekhumoro

+0

[我如何杀死PyQt4中的单一QtCore.QTimer?](http://stackoverflow.com/questions/21079941/how-can-i-kill-a-single-shot-qtcore-qtimer- in-pyqt4) –

+0

@three_pineapples。这并不能明确地回答关于停止使用静态函数开始的单次定时器的问题。 – ekhumoro

问:如果第二QTimer.singleShot()的 第一个结束之前推出,会发生什么?是第一个被杀害还是第二个 开始呢?

  • 所有定时器独立工作,所以如果两个相继启动,双方将运行直到完成。

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

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

    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_())