'model' 我在我的 ListView 委托中得到了什么?

What 'model' am I getting in my ListView delegate?

我有一个 QML ListView,我通过 JavaScript 数组对委托进行数据驱动:

ListView {
    id:mylist
    model: [ {...}, {...}, {...} ] // JS objects
    delegate: MyRow { mydata: mylist.model[index] }
}

以上代码工作正常。然而,我最初编写的代码没有按预期运行:

ListView {
    model: [ {...}, {...}, {...} ] // JS objects
    delegate: MyRow { mydata: model[index] }
}

MyRow.qml 只是一个带有自定义 属性 和一些布局子项的矩形:

Rectangle {
    property var mydata
    color:'#eeeeff'; height:20
    RowLayout {
        anchors.fill:parent
        Text { ... }
        Text { ... }
    }
}

当我在 MyRow 委托中请求 model 时,我得到了什么?它不是可以通过 index 访问的数组,也不是具有我想要的属性的对象。


编辑:如果我在委托中将 model+"" 分配给字符串 属性,我会得到 QQmlDMListAccessorData(0x13aee00).

引用 Models and Views in Qt Quick:

If there is a naming clash between the model's properties and the delegate's properties, the roles can be accessed with the qualified model name instead. For example, if a Text type had type or age properties, the text in the above example would display those property values instead of the type and age values from the model item. In this case, the properties could have been referenced as model.type and model.age instead to ensure the delegate displays the property values from the model item.

因此,model 是命名模型角色的访问者。当您没有任何命名角色时,例如,如果模型是一个数字或一个 JS 数组,Qt 无法发明一个名称;而是通过 modelData 向您提供数据。换句话说,当您的模型没有命名角色时,model 没有用。