Skip to main content
 首页 » 编程设计

python之如何删除 QTreeWidgetItem 的 child

2024年10月17日6lovecherry

如何删除 QTreeWidgetItem 的 child 。有时它会删除所有项目,有时则不会。

如何正确删除子项。

这是我执行删除子项和添加新子项的函数

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))   

在 QWidgetItem.removeChild 的文档中

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

removed item will not be deleted 是什么意思

请您参考如下方法:

您的示例不起作用,因为您试图在遍历项目时删除项目。每个项目被移除后,其他项目将向下移动。因此,一旦经过中途点,循环将开始提供无效索引。

您可以通过以相反的顺序 删除项目来轻松解决此问题。这样,在删除每个项目后,其他项目将保留在原处,所有索引将保持有效:

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

关于您关于文档的其他问题:

removeChild 方法删除传入的项目,但由调用者为其释放内存。当然,python 垃圾收集器通常会为您做这些,因此文档的这方面与 C++ 用户更相关。