是否可以停止
QTimer.singleShot()
计时器? (请不要告诉 我使用QTimer
对象的stop()
函数 - 我真的很想 知道静态函数QTimer.singleShot()
是否可以在之前停止 时间已过)如果在第二个
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/