2012-08-26 120 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