Compozitor
Compozitor

Reputation: 59

How to remove the root element from QTreeView?

I process the removal of tree elements in the slot. All elements are deleted, except the last (root).

void TreeModel::slotDelete()
{
 QStandardItem *curItem = itemFromIndex(_tvMainTree->currentIndex());
 QStandardItem *curParent = itemFromIndex(_tvMainTree->currentIndex())->parent();

 if(!curItem || !curParent) return;

 curParent->removeRow(curItem->row());
}

Why is it that when I try to delete the last element, curParent is 0x0?

Specification: I build the tree using the root element of invisibleRootItem ().

Tell me how to delete the last (root) element?

Upvotes: 0

Views: 2708

Answers (2)

Compozitor
Compozitor

Reputation: 59

Thanks to all. Here is the solution.

void TreeModel::slotDelete()
{
 QStandardItem *curItem = itemFromIndex(_tvMainTree->currentIndex());
 if(!curItem) return;

 QStandardItem *curParent = curItem->parent();
 if(!curParent)
 {
  invisibleRootItem()->removeRow(curItem->row());
  return;
 }

 curParent->removeRow(curItem->row());
}

Upvotes: 1

Murphy
Murphy

Reputation: 3999

By definition the root item is the top of a hierarchy; it can't have a parent. So what you're trying is invalid.

Seems like you're using QStandardItemModel. Compare the documentation of QStandardItemModel::invisibleRootItem():

The invisible root item provides access to the model's top-level items [...] Calling index() on the QStandardItem object retrieved from this function is not valid.

In other words: The root item/index is created implicitly; you can't delete it and have to stop recursion at this point. This is BTW a common pattern when using Qt models: If parent() returns nullptr you've reached the root index.

Upvotes: 0

Related Questions