PDA

View Full Version : Removing items properly from qtreewidget item



Djony
20th November 2006, 22:50
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....

drhex
20th November 2006, 23:06
The item's children are numbered 0 .. childCount()-1 , not 1 .. childCount()

Also, QT Objects will automatically kill their children when they die.

Djony
21st November 2006, 11:23
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

jpn
21st November 2006, 11:41
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.

Djony
21st November 2006, 12:45
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.

jpn
21st November 2006, 12:52
for (int i = 0; i < topLevelItemCount(); ++i)
{
qDeleteAll(topLevelItem(i)->takeChildren());
}

Djony
21st November 2006, 13:20
Thanx man! That solve problem. You rock!