Search code examples
pythonpysideqtreewidget

Deleting a non-toplevel item from a QTreeWidget


In the documentation, I have seen that it is possible to delete top-level items from a QTreeWidget using takeTopLevelItem(). However, I need to delete items that are not top-level. I am completely lost on how to do this, so I'm resorting here for help. Any google searches I do end without proper results and the PySide docs are being thoroughly unhelpful. I suspect there is an easy way to do this and that I'm over-thinking it, but I have no clue how to find it.


Solution

  • Okay, after thinking about it for 3 long days, I realized the answer was, as I suspected, rather simple (yet maybe a little convoluted).

    I was trying to delete the item when the QTreeWidget was right clicked (just a little background so you understand my code).

    tree = QTreeWidget()
    
    def delItem(e):
        if e.reason() == QContextMenuEvent.Mouse:
            itemClicked = tree.itemAt(e.pos())
            for topItem in range(0,tree.topLevelItemCount()):
                topItem = tree.topLevelItem(topItem)
                if topItem.isSelected():
                    tree.takeTopLevelItem(tree.indexOfTopLevelItem(topItem))
                else:
                    def checkChildren(item):
                        if item.childCount() >= 0:
                            for childItem in range(0,item.childCount()):
                                childItem = item.child(childItem)
                                if childItem.isSelected():
                                    item.removeChild(childItem)
                                else:
                                    childItem.checkChildren()
                    checkChildren(topItem)
    
    tree.contextMenuEvent = delItem