10

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

1

3 Answers 3

22

Due to advice from [email protected]#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)
9

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.

0
6

It's much easier to use Component.onCompleted:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.