I have a QAbstractItemModel
derived model attached to a QTreeView
I want to programatically append a single row to a node somewhere in my tree hierarchy.
I have a slot which is connected to a signal from my view. The signal sends the QModelIndex
of the node to which I want to append my new row. In the slot I call beginInsertRows(...)
using that QModelIndex
and the new row's row number, append the new row to my model data, and then call endInsertRows()
:
The value passed to beginInsertRows(...)
is the number of child rows the parent node has prior to appending the new node.
That is, if there are 4 child rows, they will have row indices 0, 1, 2 and 3. Therefore the new row number added will be 4.
void Model::slotOnAddRow(QModelIndex parent, std::string key)
{
assert(parent.isValid());
Row& parent_row = *static_cast<Row*>(parent.internalPointer());
beginInsertRows(parent, parent_row.numChildren(), parent_row.numChildren());
parent_row.addChildRow(key);
endInsertRows();
}
The problem I'm having is that after calling endInsertRows()
my view does not update.
Example:
Here is an example of my tree view.
Scenario:
- I want to append a new row to
SPREAD_1
. SPREAD_1
currently has 4 children rows:- 0:
inst_id
- 1:
LEG_1
- 2:
LEG_2
- 3:
LEG_3
- 0:
- The new row will therefore have row index 4, so I call
beginInsertRows(SPREAD_1, 4, 4);
I do just this, and my view does not show my new row.
Proof the node does actually exist:
I know the row exists in my model, because if I collapse the SPREAD_1
node, and then re-expand it, my newly added row is now visible:
Question:
AFAIKT I've followed the example online correctly, but I'm obviously missing something.
How can I append a new row to a tree node, and have the view update?
Do I need to emit a signal or override another base class method?