【发布时间】:2023-03-24 16:37:02
【问题描述】:
我在 Singleton 中使用 QTimer 实现了一个计时器。 Singleton 是使用Borg 模式实现的。如果我在 Singleton 的函数中单次启动 QTimer,它将不会被执行。在 Singleton 之外的函数中进行相同的调用效果很好。
这是代码:
#!/usr/bin/env python
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication
class Borg():
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Timers(Borg):
def __init__(self):
Borg.__init__(self)
def update_not_working(self):
QTimer().singleShot(2000, Timers().update_not_working)
print('update not working')
def update_working():
QTimer().singleShot(2000, update_working)
print('update working')
if __name__ == '__main__':
app = QApplication(sys.argv)
print('start timer')
Timers().update_not_working()
update_working()
sys.exit(app.exec_())
输出为(无错误,无异常):
start timer
update not working
update working
update working
....
为什么一个电话有效而另一个电话无效?我的 Borg 实现或 QTimer 的使用有问题吗?
【问题讨论】: