QML ListModel append broken for object containing

2019-09-12 05:46发布

问题:

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:

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).