pythonpyside2qtreewidgetqtreewidgetitem

QTreeWidgetItem.addChild() doesn't work in some cases?


I'm having trouble with adding a child to a top-level item in a QTreeWidget. I have a QTreeWidget in which the user can click a button to add items called "steps". It contains only two levels and is presented as in the following example:

- TreeWidget
   - step1
       - step1.1
       - step1.2
       - [add sub-step button]
   - step2
       - step2.1
       - [add sub-step button]
   - [add step button]   

So when the 'add sub-step button' is clicked, it should add a new child to the concerned top-level item just before the button it-self and it works fine. But when the 'add step button' is clicked it should add a top-level item and add a child to it, containing a new button. The problem is with adding the child for the new button.
The buttons are connected to this slot:

@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)

I have no error message but when I click the 'add step button' it only adds the top-level item and not the child item containing the button. I can't find any reason for this in the qt documentation or on google.
What I tried (but still wouldn't add a child to 'newStep'):

I am using pyside2 and it is executing in the python interpreter of Maya2018 (if this info helps)

Here is a git hub link to a reduced version of my code so you can test for yourself: addStepsExample Can someone see and explain what is wrong?


Solution

  • The problem is really simple, when a child is added to an item after the QTreeWidget is shown, these are collapsed by default, so it is not observed, the solution is to expand it:

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