2012-08-26 122 views
9

我发现很难找到一种简单的方法来删除我选择的QTreeWidgetItem在PyQt中删除QTreeWidgetItem?

我的拼凑方法包括树的当前选择设置为current然后:

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

这并不可怕,但是是不是有命令直线上升只是删除的项目?

+0

我相信你是正确的方法。在C++中,您可以简单地删除该项目,因此调用它的析构函数,并且将从该小部件中移除该项目。但我不认为有直接的方法可以从Python中做到这一点。 – Avaris

回答

10

QTreeWidget类具有invisibleRootItem()功能,其允许稍微更整洁的方法:

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

PyQt4中使用SIP来生成用于Qt类Python绑定,所以可以删除C++通过the sip python API明确地反对:

import sip 
... 
sip.delete(current) 

PySide,shiboken的绑定生成器有a similar module

+0

不错+1。我不知道。 – Avaris

+0

我会在将来使用这个,但我与其他答案一起去了。虽然谢谢! – RodericDay