0
votes

ListModel produces unexpected and pretty much broken results when trying to insert a JS object which contains an array:

property ListModel model : ListModel {}

Component.onCompleted: {
  var a = [1, 2, 3, 4, 5]
  console.log(a)
  model.append({"a" : a})
  console.log(model.get(model.count - 1))
  console.log(model.get(model.count - 1).a)

Output is:

qml: [1,2,3,4,5]
qml: QObject(0x3cccd58)
qml: QQmlListModel(0x3cd0978)

However, if the array is joined into a string, it works as expected:

  console.log(a)
  a = a.join(",")
  model.append({"a" : a})
  console.log(model.get(model.count - 1))
  console.log(model.get(model.count - 1).a)

qml: [1,2,3,4,5]
qml: QObject(0x3d5da60)
qml: 1,2,3,4,5

A few observations - it seems like the array is somehow "converted" to a QQmlListModel, and it is another list model instance, not the one that's being appended to. Also, initially I though this might indeed be some auto conversion and expected that list model to contain the five numbers and indeed count is 5, however get(0) returns an undefined. So while the size matches that of the array, there isn't any valid content whatsoever.

I am pretty sure it is a bug, but nevertheless I'd ask if someone knows what is going on before filing a bug report.

1
The array is indeed converted into a ListModel, but you have no roles defined. Try to append [ { val: 1 }, { val: 2 }, { val: 3 } ] - Now you will have something to get(0) to. - derM
Except that in that case the intent is just to have an array as data, not a model. - dtech

1 Answers

0
votes

From the ListModel docs:

The ListModel is a simple container of ListElement definitions [...]

If you then go to the documentation of ListElement:

Values must be simple constants; either strings (quoted and optionally within a call to QT_TR_NOOP), boolean values (true, false), numbers, or enumeration values (such as AlignText.AlignHCenter).