How to delete QTreeWidgetItem

后端 未结 4 2086
没有蜡笔的小新
没有蜡笔的小新 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:17

    Python is different from C++ in the sense of memory management/deleting objects. Python has a garbage collector (GC) that manages destroying of the objects automatically. That occurs when the reference count of an object reaches zero.

    del i only means 'decrement the reference count by one'. It never results in a direct call to __del__. __del__ of an object is only called when reference count reaches to zero and is about to be garbage collected. (Although this is true for CPython, it's not guaranteed for every implementation. It depends on the GC implementation. So you should not rely on __del__ at all)

    Keeping story short, the call time of __del__ is ambiguous. You should never call __del__ (or any other __foo__ special methods) directly. In fact, for the reasons above you should rather avoid the use of __del__ at all (usually).

    Apart from that, there is another issue.

    tree.removeItemWidget(i, 0)
    

    This does not remove an item from QTreeWidget. As the name suggests, it removes a widget from an item, not the QTreeWidgetItem. It's counterpart to the setItemWidget method, not the addTopLevelItem method.

    If you need to remove a specific item from the tree, you should use takeTopLevelItem.

    tree.takeTopLevelItem(tree.indexOfTopLevelItem(i))
    

    tree.clear() is fine. It will remove every top level item from the tree.

提交回复
热议问题