Search code examples
qtqtreeviewqabstractitemmodel

How do I Insert an item at top of QTreeView


In my app I'd like to insert an item at the top of a QTreeView.

What I have so far will insert an item just above the currently selected item. The code (nicked, I think, from the EditableTreeviewDemo):

QModelIndex index = this->selectionModel()->currentIndex();
QAbstractItemModel *model = this->model();

if (!model->insertRow(index.row(), index.parent()))
    return;

I guess what I need is the index to the current first row? How do I get this?

As a side question, what happens to the current index when a row is inserted? Does it continue to point to the same item, or the same row?


Solution

  • Well first you have to know that insertRow is a function from QAbstractItemModel and it will call insertRows (with an s). This function must be redefined in your model subclass if you want to allow insertion of data in your model.

    http://doc.qt.io/qt-5/qabstractitemmodel.html#insertRows

    Also consider that any parent of a topmost index is a invalid QModelIndex. Then the call to do would be :

    model->insertRow(0, QModelIndex());
    

    And because this is the default value for the second parameter, simply call :

    model->insertRow(0);
    

    Then in your redefinition of insertRows simply check the validity of you parent index to ensure you news underlying data is created where you want it to be.

    For you question, inserting data in the model won't affect the current and selected items.