【发布时间】:2018-11-28 09:31:49
【问题描述】:
我在将子项添加到 QTreeWidget 中的顶级项时遇到问题。 我有一个 QTreeWidget,用户可以在其中单击一个按钮来添加称为“步骤”的项目。它仅包含两个级别,如下例所示:
- TreeWidget
- step1
- step1.1
- step1.2
- [add sub-step button]
- step2
- step2.1
- [add sub-step button]
- [add step button]
因此,当单击“添加子步骤按钮”时,它应该在按钮本身之前向相关顶级项目添加一个新子项,并且它工作正常。但是,当单击“添加步骤按钮”时,它应该添加一个顶级项目并向其添加一个子项,其中包含一个新按钮。问题在于为新按钮添加子元素。
按钮连接到此插槽:
@Slot(int)
def addCustomStep(self, parentIndex):
newStep = QTreeWidgetItem()
newStep.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
if parentIndex == -1:
#add a top-level step with button
index = self.treeWidget.invisibleRootItem().childCount() - 1
self.treeWidget.insertTopLevelItem(index, newStep)
child = QTreeWidgetItem()
child.setSizeHint(0, QSize(0, CSTM_STEP_WIDGET_HEIGHT))
child.setFlags(Qt.ItemIsEnabled)
cstmWidget = CustomStepWidget(self.treeWidget, index) #the button
cstmWidget.click.connect(self.addCustomStep)
newStep.addChild(child) #this is the line that doesn't work for some reason
self.treeWidget.setItemWidget(child, 0, cstmWidget)
else:
#add a sub-step to parent
parentItem = self.treeWidget.invisibleRootItem().child(parentIndex)
parentItem.insertChild(parentItem.childCount() - 1, newStep)
self.treeWidget.editItem(newStep, 0)
我没有错误消息,但是当我单击“添加步骤按钮”时,它只会添加顶级项目,而不是包含该按钮的子项目。我在 qt 文档或谷歌上找不到任何原因。
我尝试了什么(但仍然不会将孩子添加到“newStep”):
- 添加一个“普通孩子”而不是自定义小部件
- 使用默认名称,因此无需编辑
- 在添加孩子之前进行编辑
- 将
newStep.addChild(child)替换为self.treeWidget.invisibleRootItem().child(index).addChild(child) - 测试将按钮添加到另一个顶级项目。例如:
self.treeWidget.invisibleRootItem().child(0)(有效)
我正在使用 pyside2,它正在 Maya2018 的 python 解释器中执行(如果此信息有帮助)
这是一个 git hub 链接到我的代码的简化版本,所以你可以自己测试:addStepsExample 有人可以查看并解释问题所在吗?
【问题讨论】:
-
@eyllanesc 我添加了一个示例链接。我会尽量减少一点。
标签: python pyside2 qtreewidget qtreewidgetitem