如果我运行此代码:
#!/usr/local/bin/ python3
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.button1 = QPushButton("1")
self.button2 = QPushButton("2")
self.setCentralWidget(self.button1)
self.button1.clicked.connect(lambda: self.setCentralWidget(self.button2))
self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1))
self.show()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())
...我得到这个输出:
Traceback (most recent call last):
File "test.py", line 16, in <lambda>
self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1))
RuntimeError: wrapped C/C++ object of type QPushButton has been deleted
我不明白为什么要删除该对象。Window 应该保持对它的引用。我已经彻底调查了这些帖子: Understanding the "underlying C/C++ object has been deleted" 错误 Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?
为什么按钮被删除?