1

发布的代码创建了一个Model/Proxy QTableView. 已为其启用了多选功能。

在此处输入图像描述

总共有四个项目。其中两个包括字符“A”。其他两个在其“项目”名称中包含字符“B”。

QPushButton按下时调用该clicked()方法。调用此方法时,首先查询Proxy Model连接到QTableView

proxyModel=self.tableview.model()

然后该方法要求 aproxyModel返回总行数:

rows=proxyModel.rowCount()

知道 a 的模型中有多少行,QTabelView它会迭代每一行。首先它是查询一个行索引:

index=proxyModel.index(row, 0)

知道它继续通过调用方法index来请求存储在变量中的值,并为它提供上一步中查询的 a (这里是变量)和标志。self.itemsdata()QModelIndexindexRole

item=proxyModel.data(index, Qt.DisplayRole).toPyObject()

'toPyObject()' 用于将从.data()方法接收到的数据转换为“常规”Python 变量。

最后它检查接收到的字符串中是否有字符“ B ”。如果是这样,它使用以下命令选择 QTableView 行:

self.tableview.selectRow(row)

现在我想要的是从代理模型的范围内获得相同的选择功能,filterAcceptsRow()如果可能的话。

如果不可能,我想知道是否有其他方法可以做到这一点……我应该使用QItemSelectionModel吗?那怎么办?

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):
        return True

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.horizontalHeader().setStretchLastSection(True)
        self.tableview.setSelectionMode(QAbstractItemView.MultiSelection)

        button=QPushButton(self)
        button.setText('Select Items with B')
        button.clicked.connect(self.clicked)

        layout = QVBoxLayout(self)
        layout.addWidget(self.tableview)
        layout.addWidget(button)
        self.setLayout(layout)

    def clicked(self, arg):
        proxyModel=self.tableview.model()

        self.tableview.clearSelection()
        rows=proxyModel.rowCount()
        for row in range(rows):
            index=proxyModel.index(row, 0)
            item=proxyModel.data(index, Qt.DisplayRole).toPyObject()
            if '_B_' in item:
                self.tableview.selectRow(row)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())
4

1 回答 1

3

您可以filterAcceptsRow()在代理模型的方法中实现选择,但这样做需要以下内容:

  1. 您的代理模型(或源模型)包含对QTableView实例的引用。
  2. 您的代理模型包含指示它是否处于活动状态的属性。这是因为您只想在单击按钮时选择表行,但filterAcceptsRow()代理模型会自动调用。因此,您可能希望在selectRow()单击按钮之前避免调用视图的方法。

要实现 #1,您可以在代理模型类中定义一个简单的 setter 方法:

def setView(self, view):
    self._view = view

当然,您还需要在MyWindow类的构造函数中调用该设置器:

proxyModel.setView(self.tableview)

实现#2 是在代理模型类的构造函数中创建此属性的简单问题

self.filterActive = False

现在你的类已经准备好了,你可以实现你想要的行为。在您的filterAcceptsRow()重新实现中,您只想选择包含'_B_'并且过滤器处于活动状态的行(即,单击按钮):

def filterAcceptsRow(self, row, parent):
    if self.filterActive and '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
        self._view.selectRow(row)
    return True

最后,您要确保单击按钮后满足这些条件,因此在您的 clicked() 方法中,您需要将proxyModel'filterActive属性设置为 True 并且您需要调用QSortFilterProxyModel类的invalidateFilter()方法以指示现有过滤器是无效,因此filterAcceptsRow()应再次调用:

def clicked(self, arg):
    proxyModel=self.tableview.model()
    self.tableview.clearSelection()
    proxyModel.filterActive = True
    proxyModel.invalidateFilter()

因此,完整的新代码是:

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__()
        self.filterActive = False

    def setView(self, view):
        self._view = view

    def filterAcceptsRow(self, row, parent):
        if self.filterActive and '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
            self._view.selectRow(row)
        return True

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.horizontalHeader().setStretchLastSection(True)
        self.tableview.setSelectionMode(QAbstractItemView.MultiSelection)

        proxyModel.setView(self.tableview)

        button=QPushButton(self)
        button.setText('Select Items with B')
        button.clicked.connect(self.clicked)

        layout = QVBoxLayout(self)
        layout.addWidget(self.tableview)
        layout.addWidget(button)
        self.setLayout(layout)

    def clicked(self, arg):
        proxyModel=self.tableview.model()
        self.tableview.clearSelection()
        proxyModel.filterActive = True
        proxyModel.invalidateFilter()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

说了这么多,目的filterAcceptsRow()让您可以在. 因此,更典型的实现(遵循您想要的规则)将是:QSortFilterProxyModel

def filterAcceptsRow(self, row, parent):
    if not self.filterActive or '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
        return True
    return False

即便如此,由于可以使用正则表达式完成过滤,因此filterAcceptsRow()甚至不需要重新实现 of。你可以调用proxyModel.setFilterRegExp(QRegExp("_B_", Qt.CaseInsensitive, QRegExp.FixedString))andproxyModel.setFilterKeyColumn(0)来实现同样的事情,过滤方式。

希望有帮助!

于 2015-01-23T15:51:50.483 回答