如何从 QItemSelection 中收集行

How do I collect rows from QItemSelection

QItemSelection 中收集每行 QModelIndex 列表的最佳方法是什么。目前 QItemSelection returns 每行每列的 QModelIndex 列表。我只需要每一行。

如果您使用的视图的 selection 行为是 select 行,最简单的方法是:

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

比上面的更短(但不会更快)的替代方法是:

from itertools import filterfalse

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

但是,如果 selection 行为是针对 select 项,则您需要这样:

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