python - QTreeWidgetItem.addChild() 在某些情况下不起作用?

标签 python pyside2 qtreewidget qtreewidgetitem

我在将子项添加到 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 文档或 google 上找不到任何原因。 我尝试过的(但仍然不会将 child 添加到“newStep”):

  • 添加“普通子项”而不是自定义小部件
  • 使用默认名称,因此无需编辑
  • 添加子项之前进行编辑
  • newStep.addChild(child) 替换为 self.treeWidget.invisibleRootItem().child(index).addChild(child)
  • 测试将按钮添加到另一个顶级项目。例如:self.treeWidget.invisibleRootItem().child(0)(有效)

我正在使用 pyside2,它正在 Maya2018 的 python 解释器中执行(如果此信息有帮助)

这里有一个 git hub 链接,指向我的代码的简化版本,以便您可以自己测试:addStepsExample 有人能看到并解释出什么问题吗?

最佳答案

问题很简单,当QTreeWidget显示后将子项添加到项目时,默认情况下这些项是折叠的,因此观察不到,解决方案是将其展开:

...
step.addChild(child) #<-- ISN'T THIS SUPPOSED TO WORK??
self.addStepsTW.setItemWidget(child, 0, cstmWidget)
step.setExpanded(True)  #<--

关于python - QTreeWidgetItem.addChild() 在某些情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50928059/

相关文章:

python - NumPy 的/科学的 : why it is throwing error

qt - 如何在 QtCreator 中分​​析 PySide2 + QML?

qt - 如何在PyQt4中为QTreeWidget实现itemChecked和itemUnchecked信号?

python - PySide QTreeWidget clear() 导致崩溃

python - 如何以pythonic方式将元组一分为二

python - 如何使用 reportlab 添加指向单词的链接?

python - 是否可以扩展 QSlider 周围的可绘制区域

python - 使用 Qt Designer 在 PySide2 中实现信号/槽时出错

python - 在 QTreeWidget 中升高和降低 QTreeWidgetItem?

python - azure 函数的有效绑定(bind)名称是什么?