How to get Index Row number from Source Model

…衆ロ難τιáo~ 提交于 2019-12-25 01:08:58

问题


Clicking the QTableView "Item_B_001" prints out its row number # 0.

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

回答1:


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


来源:https://stackoverflow.com/questions/28160584/how-to-get-index-row-number-from-source-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!