如何从源模型获取索引行号 [英] How to get Index Row number from Source Model
本文介绍了如何从源模型获取索引行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
点击QTableView
" Item_B_001 ",将打印出其行号# 0 .
Clicking the QTableView
"Item_B_001" prints out its row number # 0.
但是在源模型的self.items
中,该项目对应于数字#3.如何获取真实"源模型的项目的行号-它确实与之对应的数字?
But in source model's self.items
this item corresponds to the number # 3. How to get a "real" Source Model's Item's row number - a number it really corresponds to?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Item_A_001','Item_A_002','Item_B_001','Item_B_002']
def rowCount(self, parent=QModelIndex()):
return len(self.items)
def columnCount(self, parent=QModelIndex()):
return 1
def data(self, index, role):
if not index.isValid(): return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
row=index.row()
if row<len(self.items):
return QVariant(self.items[row])
else:
return QVariant()
class Proxy(QSortFilterProxyModel):
def __init__(self):
super(Proxy, self).__init__()
def filterAcceptsRow(self, row, parent):
if '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
return True
return False
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
tableModel=Model(self)
proxyModel=Proxy()
proxyModel.setSourceModel(tableModel)
self.tableview=QTableView(self)
self.tableview.setModel(proxyModel)
self.tableview.clicked.connect(self.viewClicked)
self.tableview.horizontalHeader().setStretchLastSection(True)
layout = QVBoxLayout(self)
layout.addWidget(self.tableview)
self.setLayout(layout)
def viewClicked(self, indexClicked):
print 'index of proxy row', indexClicked.row()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
推荐答案
我认为您可以使用QAbstractProxyModel::mapToSource()
函数在源模型中返回与代理模型中的索引相对应的模型索引. IE. (不确定Python语法):
I think you could use the QAbstractProxyModel::mapToSource()
function to return the model index in the source model that corresponds to the index in the proxy model. I.e. (not sure about Python syntax):
def viewClicked(self, indexClicked):
print 'index of proxy row', self.proxyModel.mapToSource(indexClicked).row()
这篇关于如何从源模型获取索引行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文