2017-10-20 13 views
0

このコードは、QTreeWidgetとボタンで1つのダイアログを作成します。ボタンをクリックすると、現在選択されているルート項目の子をすべて削除します。それを達成する方法?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

* Root 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) 
関連する問題