代码使用QTreeWidget和一个按钮创建一个对话框。单击该按钮时,我想删除当前所选根项目的所有子项。如何实现呢?
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 :(得分: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)