通过 QSortFilterProxyModel 的项目计数

Count of items that pass QSoftFilterProxyModel

我正在尝试从 QML 访问通过 QSortFilterProxyModel 中过滤器的项目数。我找不到任何可以缓解这种情况的内置函数。

我的方法是像这样给 FilterModel 属性:

Q_PROPERTY(int count READ rowCount NOTIFY countChanged)

并将 countChanged 信号连接到源模型 dataChanged 信号。虽然我相信这会奏效,但它似乎过于复杂。我还缺少更好的方法吗?

不,遗憾的是没有更好的方法。

要让它像那样工作,您需要将 countChanged 信号连接到您的代理模型:rowsInsertedrowsRemovedmodelResetlayoutChanged 信号。这就是我在 QML 代理模型实现中所做的:https://github.com/oKcerG/SortFilterProxyModel/blob/d2772bd6e40ce81a07712c5c320d0ff1b709ce37/qqmlsortfilterproxymodel.cpp#L33-L36

或者,我也尝试使用非侵入式 qml 模型助手作为概念证明,以友好的方式公开来自 QAbstractItemModel 的数据。它适用于模型的附加对象:https://github.com/oKcerG/QmlModelHelper (check the test for the count feature)

要查询模型的数量,您可以这样做:

myModel.ModelHelper.count,它是一个 属性,因此您将收到更改通知并与其正确绑定。