QML ListModel为字符串

时间:2018-04-04 13:25:25

标签: json qml stringify listmodel

我有一个像这样填充的ListModel:

Component.onCompleted:{
  fillListModel();
}

ListModel{
  id:listModel;
}
function fillListModel(){
  for(var i=0; i<2; i++)
    listModel.append({"aKey": "aKey"+i})
}

ComboBox{
  ...
  model:listModel  //each element of the model appears only one time
}

我想从该模型中创建一个字符串,所以我这样做:

function listModelToString(){
  var datamodel = []
  for (var i = 0; i < listModel.count; ++i){
    datamodel.push(listModel.get(i))
  }
  var keysList = JSON.stringify(datamodel)
  console.log(keysList)
}

我得到以下结果:

[{"aKey":"aKey0","aKey":"aKey0"},{"aKey":"aKey1","aKey":"aKey1"}]

为什么它将每对(aKey,aKey0),(aKey,aKey1)放在一起? 我可以乘坐&#34;额外的&#34;值得,但我想知道为什么我得到的不仅仅是:

[{"aKey":"aKey0"},{"aKey":"aKey1"}]

感谢。

修改 最小代码:

import QtQuick 2.6
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Window 2.2

ApplicationWindow {
  id: mainWindow
  width: 400
  height: 400
  visible: true

  Component.onCompleted:{
    fillListModel();
  }

  ListModel{
    id:listModel;
  }

  function fillListModel(){
    for(var i=0; i<2; i++)
      listModel.append({"aKey": "aKey"+i})
    listModelToString()
  }

  function listModelToString(){
    var datamodel = []
    for (var i = 0; i < listModel.count; ++i)
      datamodel.push(listModel.get(i))

    var keysList = JSON.stringify(datamodel)
    console.log(keysList)  //output [{"aKey":"aKey0","aKey":"aKey0"},{"aKey":"aKey1","aKey":"aKey1"}]
  }

  ComboBox{
    model:listModel  //each element of the model appears only one time
  }
}

0 个答案:

没有答案