Search code examples
qtqtreewidget

QTreeWidgetItem::insertChild does not its work


I have a QTreeWidget and I would like to insert a child at a certain index. I tried with

void QTreeWidgetItem::insertChild ( int index, QTreeWidgetItem * child )

but any index I put, it inserts the child at the end of all children the parent has.


Solution

  • I found the solution:

    My first code was this

    QTreeWidgetItem* newVtxItem = new QTreeWidgetItem(parentItem);
    newVtxItem->setText(0, "vtx 1");
    newVtxItem->setText(1, "-1");
    childOfNameProfile->insertChild(0,newVtxItem);
    

    Then I correct it by deleting the parentItem of the new QTreeWidgetItem in this way:

    QTreeWidgetItem* newVtxItem = new QTreeWidgetItem();
    newVtxItem->setText(0, "vtx 1");
    newVtxItem->setText(1, "-1");
    childOfNameProfile->insertChild(0,newVtxItem);
    

    The reason why the child was inserted after all children is because when you create a QTreeWidgetItem and defining a parent, Qt put it directly at the end of the children list of the parent. So insertChild, as the documentation said:

    If the child has already been inserted somewhere else it won’t be inserted again.
    

    I hope I could help someone. Enjoy Qt!