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.
Here is an example of my tree view.
SPREAD_1
.SPREAD_1
currently has 4 children rows:
inst_id
LEG_1
LEG_2
LEG_3
beginInsertRows(SPREAD_1, 4, 4);
I do just this, and my view does not show my new row.
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:
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?
An issue like this is indicative of an error elsewhere in the model. Without seeing the implementation of the model it is impossible to say where.
Using Model Test can be very helpful in diagnosing the issue.
Literally all you need to is instantiate a ModelTest
instance with your model
QTreeView(&_model);
ModelTest test(&_model);
If the model doesn't conform, you will get assertion failures from ModelTest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With