How to delete QTreeWidgetItem

后端 未结 4 2006
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 02:42

Several webpages say that QTreeWidgetItem can be deleted by deleting or QTreeWidget.clearing. But my code sample below doesn\'t seem to do so. Am I doi

4条回答
  •  难免孤独
    2021-02-20 03:22

    You're confusing tree items (i.e., tree nodes) with the widgets that a given item can contain.

    The following example creates a QTreeWidget and adds two items to it: a top level item and a nested one. Removing the comments you can see how both of them are removed from the tree.

    #!/usr/bin/env python
    import sys
    from PyQt4.QtGui import *
    
    class MyMainWindow(QMainWindow):
        def __init__(self, parent=None):
            super(MyMainWindow, self).__init__(parent)
            self.tree = QTreeWidget(self)
            self.setCentralWidget(self.tree)
            self.tree.setHeaderLabel('funksoul')
            i = QTreeWidgetItem(self.tree, ['top level'])   
            self.tree.addTopLevelItem(i)
            j = QTreeWidgetItem(i ,['nested level'])
            #i.takeChild(0)
            #self.tree.takeTopLevelItem(0)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        ui = MyMainWindow()
        ui.show()
        sys.exit(app.exec_())
    

    For removing both types of items from the tree you need the items index. If you have a reference to the item you want to remove you can get the corresponding index with the indexOfTopLevelItem and indexOfChild functions.

提交回复
热议问题