Removing items properly from qtreewidget item
I am using Qt 4.1, and my application works with qtreewidget. It crashes when I am destroying items from tree ( executing this code):
void Search::DeleteItem(QTreeWidgetItem *item)
{
if (!item) return;
for(int i=item->childCount(); i>0; i--) {
DeleteItem(item->child(i));
}
delete item;
}
This piece of code is meant to delete all items from qtreewidget. I am calling this method number of times equal to number of top level items. Any advice? Is there any better way to delete qtreewidgetitems from qtreewidget?
Any idea's are apreciated, I am complete newbie with Qt....
Re: Removing items properly from qtreewidget item
The item's children are numbered 0 .. childCount()-1 , not 1 .. childCount()
Also, QT Objects will automatically kill their children when they die.
Re: Removing items properly from qtreewidget item
So, if I want to delete all items in qtreewidget, I could just delete top level items? Funny, though, my application is actualy crashing when I am doing delete of my top level items. I have changed my code, and I have found out that this is the issue. What could go wrong when tring to delete top level items of qtreewidget?
Thanx for your reply
Re: Removing items properly from qtreewidget item
QTreeWidget cleans up it's content upon destruction. All items are deleted when the QTreeWidget is deleted. If you want to explicitly cleanup the tree, you can simply call QTreeWidget::clear(). The crash was caused by an incorrect index, like drhex already mentioned.
Re: Removing items properly from qtreewidget item
Yes, I just want to explicitly delete just all items except the top level ones. I am trying numerous ways and the thing is whenever I try to delete qtreewidgetitem application crashes. So, do you know any method which deletes all items and leaves top level ones? That would solve my problem.
Re: Removing items properly from qtreewidget item
Code:
for (int i = 0; i < topLevelItemCount(); ++i)
{
qDeleteAll(topLevelItem(i)->takeChildren());
}
Re: Removing items properly from qtreewidget item
Thanx man! That solve problem. You rock!