Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: View not updating after QAbstractItemModel::beginInsertRows/endInsertRows

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.

enter image description here

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
  • 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:

enter image description here

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?

like image 888
Steve Lorimer Avatar asked Oct 30 '22 18:10

Steve Lorimer


1 Answers

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

like image 187
Steve Lorimer Avatar answered Nov 15 '22 04:11

Steve Lorimer