PDA

View Full Version : QAbstractModel insert row at the top, keep current item selected



alketi
25th November 2014, 21:29
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.


QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();

if (role != Qt::DisplayRole && role != Qt::EditRole)
return QVariant();

if (index.column() == 0)
return m_data->getSize() - index.row();

return QVariant();
}

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?

wysota
25th November 2014, 22:05
You should use beginInsertRow() followed by endInsertRows() followed by dataChanged() for the first column (since data in all rows changes).

anda_skoa
26th November 2014, 06:55
You should use beginInsertRow() followed by endInsertRows() followed by dataChanged() for the first column (since data in all rows changes).
Shouldn't the begin/end insert rows duo be enough?
The value of the other rows stay the same, no?

Something like


// insert row, top level, at row 0
beginInsertRows(QModelIndex(), 0, 0);

//prepend row to m_data

endInsertRows();


Cheers,
_

wysota
26th November 2014, 09:05
Ah, right, of course.