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

16,171

Solution 1

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.

Solution 2

To delete a top level item call QTreeWidget::takeTopLevelItem method and then delete the returned item:

delete treeWidget->takeTopLevelItem(index);

Where index is index of the item to be removed.

Solution 3

Function takeChild only works with QTreeWidgetItem. With QtreeWidget, you can use QtreeWidget::takeTopLevelItem(int index)

Share:
16,171
Cameron Tinker
Author by

Cameron Tinker

I am a Computer Science graduate from LSU. I enjoy programming computers, playing piano, and playing classic video games in my spare time. Professionally, I am a full stack web developer specializing in ASP.NET MVC and ASP.NET Web API single page applications. I am well versed in C# and .NET. I enjoy learning new technologies and keeping up with the latest in the software development industry.

Updated on June 08, 2022

Comments

  • Cameron Tinker
    Cameron Tinker about 2 years

    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;
    }
    
  • Cameron Tinker
    Cameron Tinker over 12 years
    Thank you for confirming this. I have made my top level items in my QTreeWidget QTreeWidgetItem pointers in order to make reference to them throughout my code. Making them pointers makes it easy to delete them and re-initialize them if needed.