ListElement QML Type

定义ListModel 中的一个数据项 ... 更多...

Import Statement: import QtQml.Models

详细说明

List elements(列表元素)在ListModel 定义中定义,代表列表中的项目,这些项目将使用ListViewRepeater 项目显示。

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

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

从 Qt 5.11 开始,ListElement 还允许将函数声明分配给一个角色。这样就可以定义具有可调用操作的 ListElements。

引用角色

角色名称用于委托从列表元素中获取数据。每个角色名称都可在委托的作用域中访问,并指向当前元素中的相应角色。如果使用的角色名称不明确,可通过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
    }
}

委托人只需参考namecost ,就能获得每个元素的名称和成本:

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

另请参见 ListModel

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