【问题标题】:How to get Index Row number from Source Model如何从源模型中获取索引行号
【发布时间】:2015-03-25 11:36:26
【问题描述】:

点击QTableViewItem_B_001”打印出它的行号#0

但在源模型的self.items 中,此项目对应于数字#3。如何获得“真实”源模型的项目的行号——它真正对应的数字?

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

【问题讨论】:

    标签: python qt model pyqt qtableview


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      相关资源
      最近更新 更多