[SOLVED] QPersistentModelIndex usage
-
wrote on 8 Nov 2013, 19:54 last edited by
Maybe should I somehow refresh all persistent indexes after sorting?
-
wrote on 8 Nov 2013, 20:26 last edited by
I did some dirty test. Instead of qSort(), I'm moving new added item manually to destination row by:
@beginMoveRows(parent->index, 4, 4, parent->index, 0);
parent->childItems.move(4,0); // this is QList
endMoveRows();@
... and now all persistent indexes are updated automatically. So I suppose that I need to do something with persistent indexes after qSort() call. Or just call modelreset (I don't know which items changed after sort anyway) and create new persistent indexes for all items. changePersistentIndex doesn't change anything
And another question: where QPersistentModelIndex should be created? Now I'm creating it from "outside" model class (after childItems.append()) but maybe should I do this in QAbstractItemModel.createIndex() ? -
[quote author="Kobid" date="1383942370"]
And another question: where QPersistentModelIndex should be created? Now I'm creating it from "outside" model class (after childItems.append()) but maybe should I do this in QAbstractItemModel.createIndex() ?[/quote]
Since QpersistenModelIndex are a bit of an overhead i would only create them when needed. Thus outside of the model is fine, thats what they are actually for. THe modle should only create QModelIndex objects. -
wrote on 9 Nov 2013, 16:00 last edited by
Problem solved! I looked what QStandardItemModel do in sort method and I used similar algorithm. So here is complete solution if someone have same problem (note that my childs are based on QVectior, if you are using QList then you need to modify it a little):
@void HCDirModel::sortChilds(HCDirItem *p)
{
if (p->childCount()==0) return;QVector<QPair<HCDirItem*, int> > l(p->childItems.count()); for (int i=0; i < p->childItems.count(); ++i) { l[i] = QPair<HCDirItem*,int>(p->childItems[i], i); } qStableSort(l.begin(), l.end(), compareFilenameA); QModelIndexList mFrom, mTo; for (int i = 0; i < l.count(); ++i) { p->childItems[i] = l[i].first; QModelIndex from = createIndex(l[i].second, 0, l[i].first); if (persistentIndexList().contains(from)) { QModelIndex to = createIndex(i, 0, l[i].first); mFrom.append(from); mTo.append(to); } } if (!mFrom.empty()) changePersistentIndexList(mFrom,mTo);
}@
And usage:
@emit layoutAboutToBeChanged();
sortChilds(it);
emit layoutChanged();@
21/24