Important: Please read the Qt Code of Conduct -

QItemSelection::merge() is really slow

  • Hi!

    I need to select all indexes of a Controls 1 TreeView. To do this, I've written a method which traverses the tree, makes a QItemSelection at each level and merge it with the QItemSelection returned by the method :

    QItemSelection LocationModel::treeSelection() const
        QModelIndex root;
        QModelIndexList treeList;
        QItemSelection selection;
        for (int row = 0; row < rowCount(root); row++)
            treeList.push_back(index(row, 0, root));
        QItemSelection rootSelection(index(0, 0, root), index(rowCount() - 1, 0, root));
        selection.merge(rootSelection, QItemSelectionModel::Select);
        for (int i = 0; i < treeList.length(); i++) {
            QModelIndex parent = treeList[i];
            QItemSelection sel(index(0, 0, parent), index(rowCount(parent) - 1, 0, parent));
            selection.merge(sel, QItemSelectionModel::Select);
            for (int row = 0; row < rowCount(parent); row++)
                treeList.push_back(index(row, 0, parent));
        return selection;

    Then i pass this QItemSelection to the ItemSelectionModel of the TreeView.

    It works, but the performance is bad: for a 1000-items tree, it takes 2030ms!
    The bottleneck seems to be the QItemSelection::merge() method... Is it possible to optimize it? Or to use a faster method to make a selection?