如何删除QTreeWidgetItem的子项

如何删除QTreeWidgetItem的子项

问题描述:

该代码创建一个包含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

试试这个:

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)