'How do I remove selection from custom model?

I am trying to remove a selection of rows from a custom model. If I call removeRows() on the source model it works as expected but if I try to remove the indexes I get from selection something goes wrong (the result is that either the view shows an empty row, while the sorted view is completely out of sync, or removes 2 rows). While we could argue that maybe the index is no longer correct in a multi-select, this does not even work with removing a single row at a time.

I have tried removing a selected row with the same approach with a QStandardItemModel and that works as expected.

About the example: there are 2 views. one shows the source model, the other shows a sorted view of a model. Each view has a button to remove selection from the current view. My end goal would be to remove a selected row from the sorted model view, but I cannot even do it from source.

Any tips/help will be greatly appreciated

This is the delete selection code:

def delete_own_selection(original_model: MyTableModel, normal_view: QTableView):
selection = normal_view.selectionModel().selection()
selected_rows_model_indexes = {}

for item in selection:
    print(f"own selection {selection}")
    item_selection_range: QItemSelectionRange = item
    for i in item_selection_range.indexes():
        model_index: QModelIndex = i
        if model_index.row() not in selected_rows_model_indexes:
            selected_rows_model_indexes[model_index.row()] = model_index

for i in selected_rows_model_indexes.values():
    original_model.removeRows(i.row(), 1)

file containing model definition and how I call the functions in the example

Edit: I have found 2 mistakes and fixed my issue: 1st mistake in the model, where I called the beginRemoveRows with wrong parameters

2nd mistake: for selection to work I should have sorted in reverse order the index



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source