How do I collect rows from QItemSelection

2.2k views Asked by At

What is the best way to collect a list of QModelIndex per row from a QItemSelection. Currently QItemSelection returns a list of QModelIndex for each row and each column. I only need it for each row.

1

There are 1 answers

0
ekhumoro On BEST ANSWER

If you are using a view where the selection behaviour is to select rows, the simplest method would be this:

def selected_rows(self, selection):
    indexes = []
    for index in selection.indexes():
        if index.column() == 0:
            indexes.append(index)
    return indexes

A somewhat shorter (but not much faster) alternative to the above would be:

from itertools import filterfalse

def selected_rows(self, selection):
    return list(filterfalse(QtCore.QModelIndex.column, selection.indexes()))

However, if the selection behaviour is to select items, you would need this:

def selected_rows(self, selection):
    seen = set()
    indexes = []
    model = self.tree.model()
    for index in selection.indexes():
        if index.row() not in seen:
            indexes.append(model.index(index.row(), 0))
            # or if you don't care about the specific column
            # indexes.append(index)
            seen.add(index.row())
    return indexes