Delete QTreeWidgetItem in PyQt?

RodericDay picture RodericDay · Aug 26, 2012 · Viewed 10k times · Source

I'm finding it frustratingly hard to find a simple way to delete my selected QTreeWidgetItem.

My patchwork method involves setting the tree's current selection to current and then:

if current.parent() is not None:
   current.parent().removeChild(current)
else:
   self.viewer.takeTopLevelItem(self.viewer.indexOfTopLevelItem(current))

It's not horrible, but isn't there a command that straight up just removes the item?

Answer

ekhumoro picture ekhumoro · Aug 27, 2012

The QTreeWidget class has an invisibleRootItem() function which allows for a somewhat neater approach:

root = tree.invisibleRootItem()
for item in tree.selectedItems():
    (item.parent() or root).removeChild(item)