qtqt4qstandarditemmodelqstandarditem

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?


Solution

  • 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());
    }