user4442454
user4442454

Reputation:

Remove item from QStandardItem in loop

I want to remove specific children from item, my parent item is const, ie. I can't replace it with a different parent item, I have to work on the one I have. Children items have multiple levels of children by itself. I've tried this but it doesn't work.

QStringList list; // contains list of names that should be deleted
for(int row=0; row < parent->rowCount(); ++row)
{
    QStandardItem* child = parent->child(row);
    bool found = 0;
    for(size_t i = 0; i<list.size(); ++i)
    {
        if(list[i] == child->text()) // check if child should be removed
        {
            found = 1;
            break;
        }
    }
    if(!found)
    {
        parent->removeRow(row); // this breaks child ordering for next iteration
    }
}

How do I do it correctly? Thanks in advance.

Upvotes: 4

Views: 1161

Answers (1)

Werner Henze
Werner Henze

Reputation: 16726

You should not increment row when removing a row. Or if you keep incrementing it you should repair (decrease) the row count after removeRow:

parent->removeRow(row); // this breaks child ordering for next Iteration
--row;

Upvotes: 3

Related Questions