2017-10-20 158 views
0

該代碼創建一個包含QTreeWidget和一個按鈕的對話框。單擊按鈕時,我想刪除當前選定的根項目的所有子項。如何實現它?如何刪除QTreeWidgetItem的子項

enter image description here

app = QApplication([])   
class Dialog(QDialog): 
    def __init__(self, *args, **kwargs): 
     super(Dialog, self).__init__() 
     self.setLayout(QVBoxLayout()) 

     self.tree = QTreeWidget(self) 
     self.tree.setHeaderLabels(['Column name']) 
     for i in range(3): 
      root_item = QTreeWidgetItem() 
      root_item.setText(0, 'Root %s' % i) 
      self.tree.addTopLevelItem(root_item) 
      for n in range(3): 
       childItem = QTreeWidgetItem(root_item) 
       childItem.setText(0, 'Child %s' % n) 
      root_item.setExpanded(True) 

     btn = QPushButton(self) 
     btn.setText("Delete the selected Root item's child items") 
     btn.clicked.connect(self.onClick) 
     self.layout().addWidget(self.tree) 
     self.layout().addWidget(btn) 
     self.show() 

    def onClick(self): 
     current_item = self.tree.currentItem() 
     if not current_item: 
      print 'Please select root item fist' 
     elif current_item.parent(): 
      print 'Child item is selected. Please select root item instead.' 
     else: 
      print 'Root item selected. Number of children: %r' % current_item.childCount()  

tree = Dialog() 
app.exec_() 
+0

既然你已經選擇了不生孩子的項目你是顯示的圖像是一個有點混亂,我認爲,當你選擇你想一個有孩子的項目,只有你的孩子被刪除。我是對的? – eyllanesc

+0

必須選擇根項目才能刪除其子項目。如果選擇了子項目,則不會發生任何事情:它僅打印用戶必須選擇根項目的通知。 – alphanumeric

+0

當我選擇*根0 *時,我得到以下消息*請選擇根項目拳頭* – eyllanesc

回答

1

試試這個:

current_item = self.tree.currentItem() 
children = [] 
for child in range(current_item.childCount()): 
    children.append(current_item.child(child)) 
for child in children: 
    current_item.removeChild(child)