【问题标题】:Stop a QTimer.singleShot() timer停止 QTimer.singleShot() 计时器
【发布时间】:2016-12-24 02:36:37
【问题描述】:
  1. 是否可以停止QTimer.singleShot() 计时器? (请不要告诉 我要使用 QTimer 对象的 stop() 函数 - 我真的很想 知道静态函数QTimer.singleShot()之前是否可以停止 它的时间已经过去)

  2. 如果第二个 QTimer.singleShot() 在 第一个已经过去了?是第一个被杀还是第二个 而是开始了?

【问题讨论】:

标签: python python-2.7 pyqt pyqt4 qtimer


【解决方案1】:

问。如果第二个 QTimer.singleShot() 在 第一个已经过去了?是第一个被杀还是第二个 而是开始了?

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

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

  • 静态函数会创建一个处理计时器的内部对象,因此没有可用的公共 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_())
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多