本页内容

ListElement QML Type

定义ListModel 中的数据项。更多内容...

Import Statement: import QtQml.Models

详细说明

列表元素在ListModel 定义中定义,代表列表中的项目,这些项目将通过ListView 或Repeater 项显示。

列表元素的定义方式与其他 QML 元素类似,不同之处在于它们包含一组角色定义,而不是属性。角色使用与属性定义相同的语法,既定义了数据的访问方式,也包含了数据本身。

角色名称必须以小写字母开头,并且应在给定模型中的所有元素中共享。 值必须是简单常量;可以是字符串(需加引号,可选地包含在QT_TR_NOOP() 调用中)、布尔值(true、false)、数字或枚举值(例如 AlignText.AlignHCenter)。

从 Qt 5.11 开始,ListElement 还允许将函数声明赋值给角色。这使得可以定义具有可调用操作的 ListElement。

引用角色

委托使用角色名称从列表元素中获取数据。每个角色名称在委托的作用域内均可访问,并指向当前元素中的相应角色。如果角色名称的使用存在歧义,可以通过model 属性进行访问(例如,使用model.cost 代替cost )。

用法示例

以下模型定义了一系列列表元素,每个元素都包含“name”和“cost”角色及其关联的值。

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        cost: 1.95
    }
}

委托通过简单引用name 和cost 即可获取每个元素的名称和成本:

ListView {
    anchors.fill: parent
    model: fruitModel
    delegate: Row {
        Text { text: "Fruit: " + name }
        Text { text: "Cost: $" + cost }
    }
}

另请参阅 ListModel 。

© 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.