2015-01-26 52 views
0

單擊QTableViewItem_B_001」打印出其行號#。如何從源模型中獲得索引行號

但是在源模型的self.items這個項目對應的數字#3。如何得到一個「真正的」源模型的項目的行號 - 它真的對應的數字?

enter image description here

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_()) 

回答

2

我想你可以使用QAbstractProxyModel::mapToSource()功能,在對應於在代理模式索引源模型迴歸模型指數。即(不知道Python語法):

def viewClicked(self, indexClicked): 
    print 'index of proxy row', self.proxyModel.mapToSource(indexClicked).row()