PyQt:运行时错误:包装的 C/C++ 对象已被删除 [英] PyQt: RuntimeError: wrapped C/C++ object has been deleted
问题描述
如果我运行此代码:
#!/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_())
...我得到这个输出:
...I get this output:
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 应该维护对它的引用.我已经彻底调查了这些帖子:理解底层C/C++对象已被删除"错误是否可以查询 PyQt4 QObject 以确定底层 C++ 实例是否已销毁?
I do not understand why the object is being deleted. Window should maintain a reference to it. I have thoroughly investigated these posts: 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?
为什么按钮被删除了?
推荐答案
这个问题的答案可以在这里找到:Python PySide(内部 c++ 对象已删除)
This answer to this question is as found here: Python PySide (Internal c++ Object Already Deleted)
显然,使用 setCentralWidget 将一个小部件分配给 QMainWindow,然后使用 setCentralWidget 分配另一个小部件将导致底层的 c++ QWidget 被删除,即使我有一个保持对它的引用的对象.
Apparently, assigning one widget to QMainWindow using setCentralWidget and then assigning another widget with setCentralWidget will cause the underlying c++ QWidget to be deleted, even though I have an object that maintains reference to it.
注意:QMainWindow 取得控件指针的所有权并在适当的时候将其删除.
Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.
这篇关于PyQt:运行时错误:包装的 C/C++ 对象已被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!