我想知道如何在ListModel中传递数组?
好的,在QML中,我有一个ListView,我将它设置为ListModel
,如下所示:
model: ListModel
{
id: myList
ListElement
{
name: ""
card: 0
books: []
}
}
我可以通过以下方式追加:
myList.append({name:"terry", card:00100, books:["024589","865976","879582","215645"]});
但是当我试图在屏幕上输出它时,我得到了这个。
{
"card": 00100
"books": {
"objectName": "",
"count": 4,
"dynamicRoles": false
},
"name": "terry",
"name": "terry"
}
我不知道为什么我有两个名字!如何才能获得图书的价值?
我查阅了ListModel和ListElement的QML文档,找不到任何与传递数组有关的内容,所有示例都是整数或字符串。
你知道我怎么才能得到约会吗?
我使用Delegate和Component.onCompleted:{}
调用数组来解决这个问题,但是我认为这不是一种好的/正确的方法,因为代表不负责保存数据,应该在Model中完成,如果我错了,请纠正我。
耽误您时间,实在对不起。
Edit01:,谢谢您的回复,下面是我需要数组的原因:我在代表中有一个ComboBox,如下所示:
delegate: Rectangle
{
id: rowID
width: 50
height: 40
color: "#323232"
Row
{
anchors.fill: parent
anchors.leftMargin: 10
anchors.rightMargin: 10
Label{
id: nameID
text: name
font.pixelSize: 12
width: 200
wrapMode: Text.WrapAnywhere
anchors.verticalCenter: parent.verticalCenter
color: "#999"
}
Label{
anchors.verticalCenter: parent.verticalCenter
text: "out:"
font.pixelSize: 12
color: "#999"
}
ComboBox{
id: booksID
height: 20
width: 50
model: books
anchors.verticalCenter: parent.verticalCenter
}
}
}
如您所见,我正在将名称添加到Label (id: nameID),并且希望将图书提供给ComboBoxE 231
(E 132
id:booksID<代码>E 233),其中具有E 134
模型E 235,如果我将图书键设置为E 136ListElementE 237我可以如何喂养所有值?
在QML中,
ListModel
或
ListElement
文档没有提到获取所有密钥的值,对吗?它只支持基于索引号的get(int index)。
发布于 2017-07-18 05:35:01
你做错了。数组成员必须是ListElement
:
ListModel {
id: mod
ListElement {
name: "ali"
dic: [ ListElement{text:"asad-o-llah"; code: 14}, ListElement{text:"aboo torab"; code: 72}, ListElement{text:"amir al-momenin"; code: 110}]
}
}
ListView {
model: mod
anchors.fill: parent
delegate: Component {
Rectangle {
width: parent.width; height: 50
Row {
Text {
text: name
}
ComboBox {
width: 100; height: 30
model: dic //<-- set dic as model for combo box
textRole: "text" //<-- important!
onCurrentIndexChanged: {
console.log("current code is "+model.get(currentIndex).code); //<-- get code value
}
}
}
}
}
}
Component.onCompleted: {
var v = mod.get(0).dic.get(0).value; //<-- sample usage
console.log(v);
}
发布于 2019-01-31 14:36:22
作为使用ListModel和ListElement的替代方法,您还可以查看QSyncable JsonListModel QML类型。(这是一个开源组件,您可以在GitHub:https://github.com/benlau/qsyncable上找到它)
JsonListModel是一种专门的ListModel类型,可以处理例如在QML中创建或从REST服务中获取的JSON数组。它会自动将JSON同步到QML ListModel,因此使用起来非常方便:
ListView {
id: listView
anchors.fill: parent
// property for json data, used as source for JsonListModel
property var jsonData: []
// use JsonListModel as model
model: JsonListModel {
source: listView.jsonData
keyField: "id"
}
// delegate
delegate: DelegateItem { /* ... */ }
}
您还可以在这里找到一个全面的指南:JsonListModel指南
https://stackoverflow.com/questions/45156895
复制相似问题