由 Javascript 填充的 QML ListView

2022-01-19 00:00:00 qml listview javascript

我刚刚意识到(根据一些 QML Bugreport)缺少用于 ListView 的 JSON 委托.所以我有两个选择,用 Javascript 或 C++ 创建的模型填充它

I just realized that (according to some QML Bugreport) there is JSON Delegate for ListView missing. So I have two choices, fill it up by model created in Javascript or C++

特别是我需要从预定义的 URL 下载 .json 数据并将它们解析到 ListView.

Specially I need to download .json data from predefined URL and parse them to ListView.

我尝试在 Javascript 中创建对象数组并将 assoc 数组作为模型推送到 ListView,但失败了.不管我怎么修改代码.

I tried to create object array in Javascript and push assoc array to ListView as Model, but it failed. No matter how i modified the code.

那么是否只有 C++ 解决方案或者我可以通过 Javascript 制作 ListView 模型?

So is there only C++ solution or I can make ListView model by Javascript?

谢谢

我试过的代码:

return [{"name":"value"}]
return {"name":"value"}
return [["name","value"]]

问题总是:ReferenceError: Can't find variable: name

推荐答案

根据 mouli@irc.freenode.net#qt 的建议,这样做:

Due to advice from mouli@irc.freenode.net#qt do this:

文件:gui.qml

import "script.js" as Script

model: ListModel { id: list_model_id }

文件:script.js

file: script.js

function makeList(id){
    id.append({"name":"value1"});
    id.append({"name":"value2"});
}

呼叫:

Script.makeList(list_model_id)

相关文章