PDA

View Full Version : Deleting rows (children) from a qstandarditem



Valheru
28th May 2007, 11:48
I have a bit of a strange problem here. With the following code :


int rowCount = model->item( row )->rowCount();
for( int i = 0; i < rowCount; ++i ){
QList< QStandardItem* > items = model->item( row )->takeRow( i );
qDeleteAll( items );
}

every SECOND row gets deleted. I'm a bit stumped, since a quick qDebug() shows that rowCount is indeed being set to the amount of rows in the QStandardItem. And since i is only being incremented by 1 every iteration, it SHOULD delete one row every time, and not skip a row. Is this a bug in Qt4? I'm running qt-copy BTW, the patched KDE4 snapshot.

marcel
28th May 2007, 11:57
Use a while loop instead. Like this:



while(model->item( row )->rowCount() ){
QList< QStandardItem* > items = model->item( row )->takeRow( 0 );
qDeleteAll( items );
}


I'm not sure if it works, but give it a try :).

Regards

Valheru
28th May 2007, 12:06
Yes, I just realised what a silly mistake I was making :p

FMG
29th March 2012, 09:01
Thank you guys, googling around I found this thread very useful.
But in my situation some of the child items may have in turn a set of children, and my guess is I am introducing some memory leak each time I delete all the children of parent without some recursion on the grand-children. Am I wrong?

The implementation suggested above works fine, but when I try it with a kind of recursion I get an application crash.


QStandardItem * loopItem = myParentItem;
while (loopItem->rowCount())
{ QList<QStandardItem *> items = loopItem->takeRow(0);
if (items.at(0)->hasChildren()) loopItem = items.at(0);
qDeleteAll(items);
}

someone have any suggestion?
tnx,
FMG

FMG
29th March 2012, 16:04
... I got the point, obviously I can't delete an object and use it later... anyway if it can be of some interest toanyone, this is the code of the working function that deletes all the children of a QStandardItem and recusrively all the "younger" relatives, avoiding a memory leak.



//delete all children of parent;
QStandardItem * loopItem = parent; //main loop item
QList<QStandardItem *> carryItems; //Last In First Out stack of items
QList<QStandardItem *> itemsToBeDeleted; //List of items to be deleted
while (loopItem->rowCount())
{
itemsToBeDeleted << loopItem->takeRow(0);
//if the row removed has children:
if (itemsToBeDeleted.at(0)->hasChildren())
{
carryItems << loopItem; //put on the stack the current loopItem
loopItem = itemsToBeDeleted.at(0); //set the row with children as the loopItem
}
//if current loopItem has no more rows but carryItems list is not empty:
if (!loopItem->rowCount() && !carryItems.isEmpty()) loopItem = carryItems.takeFirst();

}
qDeleteAll(itemsToBeDeleted);