停止QTimer.singleShot()计时器

时间:2016-12-24 02:36:37

标签: python python-2.7 pyqt pyqt4 qtimer

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

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

1 个答案:

答案 0 :(得分:0)

  

Q值。如果第二个QTimer.singleShot()在之前启动会发生什么   第一个过去了吗?是第一个被杀或是第二个   开始了吗?

  • 所有计时器都是独立工作的,所以如果两个计时器连续启动,它们都会一直运行直到完成。
  

Q值。是否可以停止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_())
    
相关问题