Search code examples
qtmodel-view-controllerqtreeviewmodel-view

QTreeView extended selection and removal/moving multiple items


Is it permissible to implement below removal algorithm for QTreeView, where QTreeView::setSelectionMode(QAbstractItemView::ExtendedSelection);, i.e. multiple items is selectable?

QModelIndexList indexList = treeView->selectionModel()->selectedRows();
QList< QPersistentModelIndex > persistentIndexList;
for (QModelIndex const & index : indexList) {
    persistentIndexList.append(index);
}
for (QPersistentModelIndex const & persistentIndex : persistentIndexList) {
    if (!treeModel->removeRow(persistentIndex.row(), persistentIndex.parent())) {
        qWarning() << "Can't remove row" << persistentIndex;
    }
}

I think, it is possible the situation, when parent removed before the child and even persistent indexes are not valid at that moment. Am I wrong?

Must the model to check hasIndex in removeRows?


Solution

  • Every implementation of QAbstractItemModel does its best (at least it has to) to keep QPersistentModelIndexs valid when the model is changed. If the model can't calculate new location of the index it invalidates the QPersistentModelIndex. It can happen when the index is removed or a model layout or whole data was changed.

    That is why it's always neccessary to check if QPersistentModelIndex valid or not before using it.

    But QAbstractItemModel::removeRows returns bool. It means that wrong arguments can be passed to this method. If the model can't remove rows due to wrong arguments it returns false.

    So the answer to your question is yes, you should check an index in removeRows and return correct result.