薛定谔的错误:PyQt QTimer 事件仅在 startTimer() 上有断点时触发

Schrodinger's Bug: PyQt QTimer event only triggered if there was a breakpoint on startTimer()

这是一个神奇的错误:此代码的行为、打印输出和分支根据放置的断点而变化,而不是基于实际代码。

timerEvent() 中的一个断点开始。

timerEvent() 中的断点 触发。

然而,当我在 startTimer() 上设置 second 断点时——但什么都不改变,那么 timerEvent() 中的断点是 现在被激怒了。

#!/bin/python2
import sys
from PyQt4.QtGui import QMainWindow, QApplication

class SchrodingersWindow(QMainWindow):
    def __init__(self, parent=None, flags=0):
        super(QMainWindow, self).__init__(parent)
        self.startTimer(0) # Try setting a breakpoint here

    def timerEvent(self, event):
        print "Something Timer Happened" # This never gets called unless the breakpoint is set on startTimer()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    SchrodingersWindow()
    app.exec_()

薛定谔的错误。在带有 wing 调试器的 pyqt 中测试

使用多个版本的 Wing 调试器、两台计算机、Windows 和 Ubuntu 进行测试。

要对此进行测试,您需要一个 python 调试器(我推荐 Wing)python 2.7 和 PyQt4

发生这种情况是因为一旦 SchrodingersWindow() 完成,持有 window 的对象就会被删除,因为您从不存储引用。如果您在 __init__ 内调试,对象正在创建过程中并且 SchrodingersWindow() 尚未返回 - 删除尚未发生。比较

win = SchrodingersWindow()

每次执行timerEvent