如果我運行此代碼:PyQt的:RuntimeError:包裝的C/C++對象已被刪除
#!/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
我不明白爲什麼對象正在被刪除。窗口應該保持對它的引用。 我已經徹底調查這些職位: Understanding the 「underlying C/C++ object has been deleted」 error Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?
爲何按鈕被刪除?
我在QWidget的子類中遇到了類似的問題,事實證明問題是我忘記了在我的'__init__'開始時調用QWidget的'__init__'。調皮。 – spookypeanut