从 QTableView 中的选定行访问 QAbstractTableModel 中的原始索引

Access original index in QAbstractTableModel from selected row in QTableView

我正在使用 Qt5 和 PySide2 为 python 程序实现 GUI。我对 Qt 的 C++ 方面的理解没有问题,所以请随意指出与 python.

无关的 Qt 引用

我使用 QAbstractTableModel 的子类在 QTableView 中显示了一些数据。我还使用 QSortFilterProxyModel 的子类来过滤我的 table 以仅显示基础数据的一个子集,因为它是一个非常大的数据集。我为用户提供了根据某些标准仅显示部分数据的可能性。这一切都非常有效。

然后我配置了 QTableView 这样用户只能 select 完成行:

self.ui.candidatesTable.setSelectionBehavior(QTableView.SelectRows)

并且在处理 UI 的对象中,我实现了一个插槽,当 table 中的 selection 发生变化时调用该插槽:

@Slot(QItemSelection)
def handleSelectionChanged(self, item):
    hasSelection = self.ui.candidatesTable.selectionModel().hasSelection()
    if hasSelection:
        selectedRows = self.ui.candidatesTable.selectionModel().selectedRows()
        for row in selectedRows:
            print(row.row())

我的问题是 print(row.row()) 打印的值显示 当前显示的行 中的行索引。如果用户 selected 筛选条件只显示几千行中的 5 行,然后 select 第一行,print(row.row()) 将 return 0 而不是基础 QAbstractTableModel 中的原始索引。

因此我的问题如下:在这种情况下如何访问原始索引?

您必须使用 mapToSource() 方法将代理模型的 QModelIndex 映射到源模型:

@Slot(QItemSelection)
def handleSelectionChanged(self, item):
    indexes = self.ui.candidatesTable.selectedIndexes()
    proxy_model = self.ui.candidatesTable.model()    

    rows = set()
    for index in indexes:
        si = proxy_model.mapToSource(index)
        rows.add(si.row())

    for row in rows:
        print(row)  

根据@eyllanesc 之前的回答,我使用 selectedRows() 而不是 selectedIndexes() 实现了一个解决方案。后者 returns 所有选定列和行的索引,而我只对行感兴趣:

@Slot(QItemSelection)
def handleSelectionChanged(self, item):
    hasSelection = self.ui.candidatesTable.selectionModel().hasSelection()
    if hasSelection:
        selectedRows = self.ui.candidatesTable.selectionModel().selectedRows()
        for row in selectedRows:
            proxy_model = self.ui.candidatesTable.model()
            row_index = proxy_model.mapToSource(row).row()