开发者

QML ListView filled by Javascript

开发者 https://www.devze.com 2023-03-01 12:23 出处:网络
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++

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++

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

I tried to create object array in Javascript and push assoc array to ListView as Model, but i开发者_JAVA技巧t failed. No matter how i modified the code.

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

Thanks

Code I tried:

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

The issue was always: ReferenceError: Can't find variable: name


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

file: gui.qml

import "script.js" as Script

model: ListModel { id: list_model_id }

file: script.js

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

call:

Script.makeList(list_model_id)


It may be a little late, but with Qt 5.5 (maybe earlier, but testet with 5.5) you can do the following:

Lets assume you have got an array like this:
var dataArray = [{"name":"A"},{"name":"B"},{"name":"C"}]

The code in QML to display this model:

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 property for more information.


It's much easier to use Component.onCompleted:

model: ListModel {
    Component.onCompleted: {
        append({"name": "A"});
        append({"name": "B"});
        append({"name": "C"});
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消