1

I have a class derived from QAbstractListModel based on a QMap<QUuid, CustomObject> which I am visualizing with ListView in qml. Some time during my applications running time I am removing some items from this map based on it's QUuid. When I am doing the removing I would like to call beginRemoveRows so the ListView is notified that it's content is changing and needs to redraw itself. How do I find out the right indexes for beginRemoveRows?

Silex
  • 2,583
  • 3
  • 35
  • 59
  • 1
    Instead of maintaining QList by yourself, you can obtain a list of keys by QMap::keys() – user2155932 Mar 11 '16 at 10:07
  • That is a good idea, going to try it out! Thanks! – Silex Mar 11 '16 at 13:37
  • I just read the docs and also tested the `QMap::keys()` and unfortunately it won't work, because it gives back a sorted list of the id's, therefore if I remove and then add a new item in the `QMap` the index of the new item might not be the last index, which then could change the index of several other items in my `QMap`. I have to obtain exactly the same index which I added with `beginInsertRow`, because that is what `ListView` is aware of. – Silex Mar 11 '16 at 15:06
  • @Silex, QMap is a sorted container, so whenever you insert a new item in it, it is placed in the right position, so it's quite natural that inserting or removing items from QMap change its items "indices". For me it seems like you are trying to achieve your goal with improper tools. You might perhaps elaborate on why you need QMap for that. – rightaway717 Mar 13 '16 at 22:07
  • The class has some already written logic which depends on the `QMap`. It would be too much work to rewrite it to a different container, but I had to derive it from `QAbstractListModel` so it can be used up in a ListView. The corresponding `QList` index structure works perfectly though. – Silex Mar 13 '16 at 22:30
  • Actually I just found out that it doesn't matter if `QMap` is sorted, I just need to find the right index anytime I do an insertion or removal, – Silex Mar 17 '16 at 01:04

1 Answers1

4

Actually using QMap is perfectly fine. You just have to find out the right indexes beginIndexRow, beginRemoveRows etc. For example finding the index for beginIndexRow looks something like this:

int index = std::distance(myQMap.begin(), myQMap.lowerBound(id));
beginInsertRows(QModelIndex(), index, index);
myQMap[id] = myCustomObject;
endInsertRows();
Silex
  • 2,583
  • 3
  • 35
  • 59