由 Javascript 填充的 QML ListView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5818334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
QML ListView filled by Javascript
提问by Marek Sebera
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++
我刚刚意识到(根据一些 QML 错误报告)缺少 ListView 的 JSON 委托。所以我有两个选择,用 Javascript 或 C++ 创建的模型填充它
Specially I need to download .json data from predefined URL and parse them to ListView.
特别是我需要从预定义的 URL 下载 .json 数据并将它们解析为 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.
我试图在 Javascript 中创建对象数组并将 assoc 数组作为模型推送到 ListView,但它失败了。无论我如何修改代码。
So is there only C++ solution or I can make ListView model by Javascript?
那么只有 C++ 解决方案还是我可以通过 Javascript 制作 ListView 模型?
Thanks
谢谢
Code I tried:
我试过的代码:
return [{"name":"value"}]
return {"name":"value"}
return [["name","value"]]
The issue was always: ReferenceError: Can't find variable: name
问题一直是: ReferenceError: Can't find variable: name
回答by Marek Sebera
Due to advice from [email protected]#qt do this:
由于 [email protected]#qt 的建议,请执行以下操作:
file: gui.qml
文件:gui.qml
import "script.js" as Script
model: ListModel { id: list_model_id }
file: script.js
文件:script.js
function makeList(id){
id.append({"name":"value1"});
id.append({"name":"value2"});
}
call:
称呼:
Script.makeList(list_model_id)
回答by Felix
It may be a little late, but with Qt 5.5 (maybe earlier, but testet with 5.5) you can do the following:
可能有点晚了,但是使用 Qt 5.5(可能更早,但使用 5.5 的 testet)您可以执行以下操作:
Lets assume you have got an array like this:var dataArray = [{"name":"A"},{"name":"B"},{"name":"C"}]
让我们假设你有一个这样的数组:var dataArray = [{"name":"A"},{"name":"B"},{"name":"C"}]
The code in QML to display this model:
QML 中显示此模型的代码:
ListView {
model: dataArray //the array from above
delegate: Label {
text: dataArray[index].name
}
}
The index
will be provided for the delegate. It's the index for the current item inside the model. See ListView delegate propertyfor more information.
该index
会提供的委托。它是模型中当前项目的索引。有关更多信息,请参阅ListView 委托属性。
回答by Mitch
It's much easier to use Component.onCompleted
:
使用起来要容易得多Component.onCompleted
:
model: ListModel {
Component.onCompleted: {
append({"name": "A"});
append({"name": "B"});
append({"name": "C"});
}
}