Reputation: 327
I am trying to delete QStandardItems
from QStandrditemModel
using QPersistentIndex
. Items are successfully deleted, but when iterate through the model the deleted rows appear without any data.
I am using the following code to delete the items:
QList<QPersistentModelIndex> selectedIndexes;
foreach (const QModelIndex &modelIndex, this->selectionModel()->selectedIndexes())
{
selectedIndexes << modelIndex;
}
foreach (const QPersistentModelIndex &index, selectedIndexes)
{
QPersistentModelIndex parentIndex = index.parent();
model->removeRow(index.row(),parentIndex);
}
// In another function
foreach (const QModelIndex &index, this->selectionModel()->selectedIndexes())
{ // do soemthing and the items appear without any data as shown
// in the image below
}
Upvotes: 1
Views: 1454
Reputation: 2444
What I found is that deleting the items doesn't seem to properly clean up the model. I experimented with various workarounds, and the one that worked is this:
QList <QStandardItem *> items = ...some list of items to remove...
for (int i = 0; i < items.count (); i++)
{
QStandardItem *parent = items[i]->parent ();
if (parent)
{
QList <QStandardItem *> row_items = parent->takeRow (items[i]->row ());
qDeleteAll (row_items);
}
}
Using "takeChild" didn't work, nor did any other mechanism I tried. Without digging through the Qt code, what seems to be happening is that deleting a single item isn't removing the row containing that item even when it's the only item in the row.
In my case, I only ever have one item per row, so the above code is safe, but if there's any possibility that the "items" list contains two or more items on the same row, then the above code would be unstable since the act of removing the first item that's encountered in the list would be deleting another item as well.
Upvotes: 1