14

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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
RodericDay
  • 1,266
  • 4
  • 20
  • 35
  • I believe yours is the correct way. In C++ you could simply delete the item, therefore invoking its destructor, and that will remove the item from the widget. But I don't think there is a direct way to do that from Python. – Avaris Aug 26 '12 at 22:25

2 Answers2

16

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)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
10

PyQt4 uses sip to generate the python bindings for Qt classes, so you can delete the C++ object explicitly through the sip python API:

import sip
...
sip.delete(current)

The binding generator for PySide, shiboken, has a similar module.

alexisdm
  • 29,448
  • 6
  • 64
  • 99