How do I delete a top level QTreeWidgetItem from a QTreeWidget?

Cameron Tinker picture Cameron Tinker · Feb 22, 2012 · Viewed 15k times · Source

I'm attempting to remove a top level tree widget item if there are no child nodes within the top level item. What is the correct way to do this? I can't seem to find the API call within Qt's documentation. Is it safe to just call delete on the top level tree widget item? I haven't run into any issues yet, but I'd like to know if that's safe practice. Thanks much.

if(topLevelTreeWidgetItem->childCount() > 1) {
  topLevelTreeWidgetItem->removeChild(childItem);
}
else
{
  delete topLevelTreeWidgetItem;
}

Answer

Chris picture Chris · Feb 22, 2012

deleteing a QTreeWidgetItem directly is perfectly safe.

According to the documentation for ~QTreeWidgetItem():

Destroys this tree widget item. The item will be removed from QTreeWidgets to which it has been added. This makes it safe to delete an item at any time.

I've used delete on many QTreeWidgetItems in practice and it works quite well.