3

How to remove children of QTreeWidgetItem. Sometimes it removes all the items and sometimes it doesn't.

How to properly delete child items.

Here is my function performing removal of child items and adding new child items

def update_children_cont(self,subDirs,parent):
    new_dir = subDirs
    for i in range(parent.childCount()):
        parent.removeChild(parent.child(i))
    print "child count should be 0",parent.childCount()
    parent.addChildren(self.tree_list_generator(new_dir))  

in docs for QWidgetItem.removeChild

Removes the given item indicated by child. The removed item will not be deleted.

what does it mean by removed item will not be deleted

Harwee
  • 1,601
  • 2
  • 21
  • 35

1 Answers1

4

Your example doesn't work because you are trying to remove items while iterating over them. After each item is removed, the others will move down. So once the half-way point is passed, the loop will start giving invalid indexes.

You can easily fix this by removing the items in reverse order. That way, after each item is removed, the other items will stay where they are and all the indexes will remain valid:

    for i in reversed(range(parent.childCount())):
        parent.removeChild(parent.child(i))

As for your other question about the docs:

The removeChild method removes the item that is passed in, but it's up to the caller to release the memory for it. Of course, the python garbage-collector will usually do that for you, so that aspect of the docs is more relevant to C++ users.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Actually I feel stupid now, I don't know why I didn't think of that – Harwee Jun 30 '16 at 13:09
  • 2
    Actually you can just remove the first item each time `for i in range(parent.childCount): parent.removeChild(parent.child(0))` because the next one will shift up so there's no need for reversal. – retnikt Dec 23 '18 at 21:00