我正在使用QSortFilterProxyModel来过滤来自QAbstractListModel的结果。但是,我想返回原始模型中不存在的第一个条目,也就是说,这是以某种方式进行的。

这是我到目前为止的内容:

class ActivedAccountModel(QSortFilterProxyModel):
    def __init__(self, model, parent=None):
        super(ActiveAccountModel, self).__init__(parent)
        self.setSourceModel(model)
        self.setDynamicSortFilter(True)

    def data(self, index, role=Qt.DisplayRole):
        account_info = super(ActiveAccountModel, self).data(index, Qt.UserRole).toPyObject()
        if role == Qt.DisplayRole:
            return account_info.name
        elif role == Qt.UserRole:
            return account_info
        return None

    def filterAcceptsRow(self, source_row, source_parent):
        source_model = self.sourceModel()
        source_index = source_model.index(source_row, 0, source_parent)
        account_info = source_model.data(source_index, Qt.UserRole)
        return isinstance(account_info.account, Account) and account_info.account.enabled

这将以以下形式返回列表:
Account 1
Account 2
...

想要在返回的列表f元素的开头返回一个额外的元素:
Extra Element
Account 1
Account 2
...

我试图重新实现rowCount以便返回实际的rowCount()+ 1,但是以某种方式我需要移动所有项才能返回索引0处的该人造元素,而我在那里有点迷失了。

有什么线索吗?到目前为止,我找不到任何相关的代码示例...谢谢!

最佳答案

我这样做只是在工作中,所以我不能给你太多代码。我可以给你大致的思路。

如果您将QAbstractProxyModel子类化,则它会更好地工作,它是为一般操作而不是排序或过滤而设计的。您将要覆盖rowCount,还需要覆盖columnCount(尽管那应该只返回源模型中的信息)。您将需要覆盖数据功能并为第一行返回自己的数据,或者再次调用源模型。

您将要覆盖mapFromSource和mapToSource函数,以允许在代理模型索引和源模型索引之间进行切换。

为了实现可靠的实现,您需要创建一些插槽并连接到源模型的信号,以进行数据更改,模型重置以及即将插入/移除的行/列。然后,您应该发出自己的信号,以使其适应额外的行。

在我们的类里面,我们使第一行的文本可设置,因此我们可以在不同情况下使用相同的代理模型。值得为您进行研究,因为它只需花费很少的精力。

编辑

根据评论请求,粗略看一下mapToSource和mapFromSource。这大约是您需要考虑的。

// Remember that this maps from the proxy's index to the source's index,
// which is invalid for the extra row the proxy adds.
mapToSource( proxy_index ):
    if proxy_index isn't valid:
        return invalid QModelIndex
    else if proxy_index is for the first row:
        return invalid QModelIndex
    else
        return source model index for (proxy_index.row - 1, proxy_index.column)

mapFromSource( source_index ):
    if source_index isn't valid:
        return invalid QModelIndex
    else if source_index has a parent:
        // This would occur if you are adding an extra top-level
        // row onto a tree model.
        // You would need to decide how to handle that condition
        return invalid QModelIndex
    else
        return proxy model index for (source_index.row + 1, source_index.column)

关于python - QSortFilterProxyModel返回人工行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3730117/

10-11 23:14
查看更多