如何从源Mod获取索引行号

2024-04-24 12:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

单击QTableView项”“将打印出其行号#0。在

但是在源模型的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_())

Tags: importselfindexreturnifinitdefsys
1条回答
网友
1楼 · 发布于 2024-04-24 12:31:56

我认为您可以使用QAbstractProxyModel::mapToSource()函数返回源模型中与代理模型中的索引相对应的模型索引。一、 e.(不确定Python语法):

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

相关问题 更多 >