首页 > 解决方案 > 创建动态 ListModel 是 QML

问题描述

我一直在尝试用我拥有的列表中的数据填充 QML 中的 ListView,但在文档中它没有显示如何动态填充 ListModel 或 ListView。列表中的数据不断变化,我打算实时更新列表,这就是我不需要硬编码模型的原因。

根据教程,这有效:

        Rectangle {
            anchors.horizontalCenter: parent.horizontalCenter
            color: "black"
            height: 500
            width: 0.95 * parent.width
            ListView {
                anchors.fill: parent
                model: fruitModel
                delegate: fruitDelegate
            }
        }

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

        Component {
            id: fruitDelegate
            Row {
                spacing: 10
                Text { text: name; color: "white" }
                Text { text: '$' + cost; color: "white" }
            }
        }

但这不会:

userModel : ["Tony", "Stark"] //list containing names of users
Rectangle {
            anchors.horizontalCenter: parent.horizontalCenter
            color: "black"
            height: 500
            width: 0.95 * parent.width
            ListView {
                anchors.fill: parent
                model: userModel // a list containing all users
                delegate: fruitDelegate
            }
}

Component {
            id: fruitDelegate
            Row {
                spacing: 10
                Text { text: name; color: "white" }
            }
}

标签: qtqml

解决方案


角色定义了如何访问信息,例如fruitModel 有2 个角色:名称和成本。但是当使用列表作为模型时,您必须使用modelData角色来访问信息:

Component {
    id: fruitDelegate
    Row {
        spacing: 10
        Text { text: modelData; color: "white" }
    }
}

ListModel 可以通过append函数更新:

Rectangle {
    anchors.horizontalCenter: parent.horizontalCenter
    color: "black"
    height: 500
    width: 0.95 * parent.width
    ListView {
        anchors.fill: parent
        model: fruitModel
        delegate: fruitDelegate
    }
}

ListModel {
    id: fruitModel
    Component.onCompleted: {
        fruitModel.append({"name": "Tony"})
        fruitModel.append({"name": "Stark"})
    }
}

Component {
    id: fruitDelegate
    Row {
        spacing: 10
        Text { text: name; color: "white" }
    }
}

推荐阅读