qtqlistviewselectionmodelqmodelindex

Invert selection on QListView


I have a QListView and I have already set a model to it. How can I implement a method for invert selection?

I have already tried making a new QItemSelection that contains all the items of my model in order to call ui.listView->selectionModel()->select(selection, QItemSelectionModel::Toggle); but my QItemSelection returns empty.

I have also thought of using the same method for each QModelIndex of my model, but I found no way to get a list of all QModelIndex of my model.

Any ideas?


Solution

  • I finally found it. It is all about understanding QModelIndex and not asking the model for its items. First thing is to get the QModelIndex that is the root of the current level/branch of the QListView and then get the QModelIndexs of the first and last children of this root QModelIndex. After that you can easily create a new QItemSelection that contains every child of this root. Finally you use this QItemSelection to toggle the selection-model of the QListView.

    void BrowserWidget::invertSelection() {
        QModelIndex rootIndex = ui.listView->rootIndex();
        QModelIndex first = rootIndex.child(0, 0);
        int numOfItems = m_itemsModel->rowCount(rootIndex);
        QModelIndex last = rootIndex.child(numOfItems - 1, 0);
    
        QItemSelection selection(first, last);
        ui.listView->selectionModel()->select(selection, QItemSelectionModel::Toggle);
    }