I have a very simple QAbstractModel for a flat QTreeView (no children).

I use an external data structure to return a value for the data() method, shown below.

Qt Code:
  1. QVariant MyModel::data(const QModelIndex &index, int role) const
  2. {
  3. if (!index.isValid())
  4. return QVariant();
  5.  
  6. if (role != Qt::DisplayRole && role != Qt::EditRole)
  7. return QVariant();
  8.  
  9. if (index.column() == 0)
  10. return m_data->getSize() - index.row();
  11.  
  12. return QVariant();
  13. }
To copy to clipboard, switch view to plain text mode 

This just simply provides a reverse ordered list for the first column, with the newest numbers arriving on top. AKA --

4
3
2 <-- User has this selected
1

So, when new data arrives, my m_data vector is incremented (outside of the model), and I call layoutChanged() on the model.

The issue is that I want the user to be able to select a particular item, say #2, and have that selection stay on #2, even when a 5th element is added to the top.

What happens is that the selection doesn't follow the item, but rather stays in the same position -- presumably because the items aren't being "inserted" correctly.

5
4
3 <-- Selection stays here: in the same list position when a 5th item is added
2 <-- I want the selection to remain with the number that was previously selected
1

I've tried various combinations of beginInsertRows(), endInsertRows(), layoutAboutToBeChanged(), to no avail.

I've even thought of trying to store the current selection and replace it after adding data, though I suspect this will fire some selection events that I'll need to filter.

Is there an easy way to handle this without embedding the data structure inside the model?