执行两次功能时Pyside崩溃

时间:2017-02-08 14:43:49

标签: python pyside

当我运行setup_controls()函数两次时,为什么我的应用程序崩溃。

我错过了一个父母/自我'某个在设计中至关重要的地方?

enter image description here

import sys
from PySide import QtGui, QtCore

class QCategoryButton(QtGui.QPushButton):
    def __init__(self, Text, treeitem, parent=None):
        super(QCategoryButton, self).__init__(Text, parent)
        self.treeitem = treeitem

    def mousePressEvent(self, event):
        mouse_button = event.button()
        if mouse_button == QtCore.Qt.LeftButton:
            self.treeitem.setExpanded(not self.treeitem.isExpanded())

class Example(QtGui.QWidget):

    def __init__(self,):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        # formatting
        self.resize(300, 300)
        self.setWindowTitle("Example")

        # widgets
        self.ui_treeWidget = QtGui.QTreeWidget()
        self.ui_treeWidget.setRootIsDecorated(False)
        self.ui_treeWidget.setHeaderHidden(True)
        self.ui_treeWidget.setIndentation(0)

        self.setup_controls()
        # self.setup_controls()

        # layout
        self.mainLayout = QtGui.QGridLayout(self)
        self.mainLayout.addWidget(self.ui_treeWidget)
        self.show()    

    def setup_controls(self):
        # Add Category
        pCategory = QtGui.QTreeWidgetItem()
        self.ui_treeWidget.addTopLevelItem(pCategory)
        self.ui_toggler = QCategoryButton('Settings', pCategory)
        self.ui_treeWidget.setItemWidget(pCategory, 0, self.ui_toggler)

        pFrame = QtGui.QFrame(self.ui_treeWidget)
        pLayout = QtGui.QVBoxLayout(pFrame)
        self.ui_ctrl = QtGui.QPushButton('Great')
        self.ui_ctrlb = QtGui.QPushButton('Cool')
        pLayout.addWidget(self.ui_ctrl)
        pLayout.addWidget(self.ui_ctrlb)

        pContainer = QtGui.QTreeWidgetItem()
        pContainer.setDisabled(False)
        pCategory.addChild(pContainer)
        self.ui_treeWidget.setItemWidget(pContainer, 0, pFrame)

# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

setItemWidget方法获取传递给它的窗口小部件的所有权。如果你没有保留引用它,它可能会被Python垃圾收集。但是当然Qt对Python一无所知,所以当它随后尝试访问不再存在的小部件时......繁荣!

这是有问题的一行:

#define check 0

在第二次调用时,存储在 self.ui_toggler = QCategoryButton('Settings', pCategory) 中的上一个窗口小部件将被删除,因为没有其他引用(在Python端)。所以你应该这样做:

self.ui_toggler