我想知道如何在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"
}
我不确定为什么我会得到2个名字!以及如何获得书籍的价值?
我查找了ListModel的QML文档,并且ListElement找不到与传递数组有关的任何内容,所有示例都是整数或字符串。
知道如何获取日期吗?
我确实通过用
Component.onCompleted:{}
调用Delegate中的数组来解决该问题,但是我认为这不是一种好方法,因为Delegate不负责保存数据,应该在Model中完成,如果我做错了,请更正我。谢谢你的时间。
Edit01:感谢您的答复,这是我需要数组的原因:
我在Delegate中有一个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),并且要将书籍提供给具有模型的ComboBox(id:booksID),如果我将书籍的键设为ListElement,那么如何提供所有值?
在QML ListModel或ListElement文档中,没有提到任何有关正确获得所有密钥值的内容吗?它仅支持基于索引号的
get(int index)
。 最佳答案
你做错了数组成员必须为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);
}