PyQt: RuntimeError: wrapped C/C++ object has been deleted

放肆的年华 提交于 2019-11-29 09:28:51
Brian

This answer to this question is as found here: Python PySide (Internal c++ Object Already Deleted)

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.

Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.

Brain's answer explains the problem perfectly. This Link explain things in more detail.

My solution to this problem was to set the widgets as attributes of the object (e.g. simply using self.label = ... instead of label = ... in your class methods). You might want to do the same for any layouts attached to the widget.

This way you create a copy of the widget so that when C++ memory cleanup occurs, you still have a reference to the widget.

Hope this helps.

In another case, the solution was to add all child objects to a detached layout first, and adding the layout to the parent layout as the last step. That is:

    l = QGridLayout()
    l.addWidget(QLabel("child1"), 0, 0)
    l.addWidget(QLabel("child2"), 0, 1)
    ...
    parentLayout.addLayout(l)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!