How to insert child into QTreeWidget hierarchy?

MaxNes picture MaxNes · Sep 19, 2014 · Viewed 10.3k times · Source

Consider I have QTreeWidget with following items hierarchy:

top_item
  |--child

Every item has assigned with setItemWidget() widget. I need to insert another child between my first two elements like this :

top_item
  |--another_child
     |--child

I trying to do that with following code:

QTreeWidgetItem* top_item = new QTreeWidgetItem;
ui->treeWidget->addTopLevelItem(top_item);
QTreeWidgetItem* child_item = new QTreeWidgetItem;
top_item->addChild(child_item);

ui->treeWidget->setItemWidget(top_item, 0, new QPushButton);
ui->treeWidget->setItemWidget(child_item, 0, new QPushButton);

// ---- let's insert another child ----
auto last_children = top_item->takeChildren();

QTreeWidgetItem* another_child_item = new QTreeWidgetItem;
top_item->insertChild(0, another_child_item);
ui->treeWidget->setItemWidget(another_child_item, 0, new QPushButton);

another_child_item->addChildren(last_children);

It works fine except one moment — it lost assigned widgets. I've tried to take and save the widgets before taking children with

QWidget* widget_from_child_item = ui->treeWidget->itemWidget(child_item, 0);
ui->treeWidget->removeItemWidget(child_item, 0);

but after calling takeChildren() all assigned widgets have been deleted and app is crashing after reassigning the widgets with setItemWidget().

What is my mistake?

Answer

Rémi picture Rémi · Sep 20, 2014

Another way to do the same thing:

QTreeWidgetItem *child = ui->treeWidget->currentItem();
QTreeWidgetItem *parent = child->parent();

if(parent)
{
    QTreeWidgetItem *another_child = new QTreeWidgetItem();
    another_child->setText(0,"another_child");
    parent->addChild(another_child);
    another_child->addChild(parent->takeChild(parent->indexOfChild(child)));
}