本页内容

FunctionSorter QML Type

根据指定“compare”方法的评估结果,对SortFilterProxyModel 中的数据进行排序。更多...

Import Statement: import QtQml.Models
Since: Qt 6.10
Inherits:

Sorter

Status: Deprecated since 6.12

自 QtQml.Models 6.12 起,此类型已被废弃。我们强烈建议不要在新代码中使用它。

详细描述

FunctionSorter允许用户定义指定的“compare”方法,该方法将被调用以对数据进行排序。该方法接受两个指定参数类型的参数(lhs和rhs),用户可通过以下方式访问数据以进行评估:

SortFilterProxyModel {
    sourceModel: model
    sorters: [
        FunctionSorter {
            id: functionSorter
            component RoleData: QtObject {
                property real age
            }
            function compare(lhsData: RoleData, rhsData: RoleData) : int {
                return (lhsData.age < rhsData.age) ? -1 : ((lhsData === rhsData.age) ? 0 : 1)
            }
        }
    ]
}

警告: compare 方法的两个参数都 必须带有显式类型注释,如上例中的lhsData 和rhsData 所示,且这两个注释必须解析为同一类型。 采用普通 JavaScript 方式编写且未添加参数类型注解的compare 方法(例如function compare(lhsData, rhsData) : int { ... } ),虽然编译时不会报错,但在比较时会失败。FunctionSorter 依赖于类型注解来确定应为lhsData 和rhsData 实例化并填充何种角色数据对象;若无类型注解,则无对象可实例化。

注意: sort 方法 已被废弃。请将其重命名为compare 。

注意: compare 函数 必须恰好包含两个显式类型注解且类型匹配的参数,并具有显式的: int 返回类型。如果未满足这些要求,排序器将发出警告并提前返回。

注意: 每当指定“compare”方法中使用的任何外部 QML 属性发生变化时,用户 都需要显式调用SortFilterProxyModel::invalidateSorter 。此行为未来可能会发生变化,例如采用隐式失效机制,届时用户便无需显式调用SortFilterProxyModel::invalidateSorter 。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.