我正在使用Qt5和PySide2为python程序实现GUI。我对理解Qt的C ++方面没有任何问题,所以请随时指出与python不相关的Qt引用。
我具有使用QTableView
的子类在QAbstractTableModel
中显示的一些数据。我还使用QSortFilterProxyModel
的子类来过滤表,以仅显示基础数据的子集,因为它是一个非常大的数据集。我为用户提供了根据某些条件仅显示部分数据的可能性。这一切都很好用。
然后我已经配置了QTableView
,以便用户只能选择完整的行:
self.ui.candidatesTable.setSelectionBehavior(QTableView.SelectRows)
并且在处理UI的对象中,我实现了一个插槽,当表中的选择更改时将调用该插槽:
@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())
打印的值显示了当前显示的行中的行索引。如果用户选择的过滤条件仅显示数千行中的5行,然后选择第一行,则print(row.row())
将返回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()
实现了一个解决方案。后者返回所有选定列和行的索引,而我只对行感兴趣:
@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()