Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML ListView filled by Javascript

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

like image 604
Marek Sebera Avatar asked Apr 28 '11 12:04

Marek Sebera


3 Answers

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)
like image 165
Marek Sebera Avatar answered Nov 10 '22 12:11

Marek Sebera


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.

like image 9
Felix Avatar answered Nov 10 '22 11:11

Felix


It's much easier to use Component.onCompleted:

model: ListModel {
    Component.onCompleted: {
        append({"name": "A"});
        append({"name": "B"});
        append({"name": "C"});
    }
}
like image 6
Mitch Avatar answered Nov 10 '22 11:11

Mitch