Qitemselectionmodel: How to Fix Getting qmodelindexlist program crash Issue

There are no trivial things in work: turning a stone into gold and a drop into a river. Only by taking everything you do seriously can you overcome all difficulties and achieve success.

The program crashed when using QT’s qitemselectionmodel to get qmodelindexlist in the project.

Usage scenario:

QItemSelectionModel *selections =pTreeView->selectionModel();
QModelIndexList selectedindexes = selections->selectedRows();

In this way, an error will be reported after calling.

Solution: find the source code of selectedrows and implement the currently selected item by yourself

    QItemSelectionModel *selections = pTreeView->selectionModel();

    QModelIndexList selectedindexes;
    //the QSet contains pairs of parent modelIndex
    //and row number
    QSet<QPair<QModelIndex, int>> rowsSeen;

    const QItemSelection ranges = selections->selection();
    for (int i = 0; i < ranges.count(); ++i)
    {
        const QItemSelectionRange& range = ranges.at(i);
        QModelIndex parent = range.parent();
        for (int row = 0; i < range.top(); row <= range.bottom(); row++)
        {
            QPair<QModelIndex, int> rowDef = qMakePair(parent, row);
            if (!rowsSeen.contains(rowDef))
            {
                rowsSeen << rowDef;
                if (selections->isRowSelected(row, parent))
                {
                    selectedindexes.append(pModel->index(row, 0, parent));
                }
            }
        }
    }

Similar Posts: