Tuesday, November 21, 2017

QML ListModel is not a QML List Type

As 0 be 1 cannot be (from Star Wars parlance), a QML ListModel is not a list QML Basic Type. Given that said, let's say you have a properly populated ListModel of coordinates (i.e. pairs of latitude and longitude values), and you want to use it as input for a QML MapPolyline to display a polyline in a map...
Well, you cannot use your ListModel directly to the path property, as it expects a list of coordinates. In such case, you can "flatten" or convert the ListModel into the proper list. Tip: the magic happens in function Map.asList()

ListModel
{ id: myListModel
ListElement
{
latitude: -28.9
longitude: 25.1
}
ListElement
{
latitude: -28.2
longitude: 25.3
}
ListElement
{
latitude: -28.4
longitude: 25.5
}
ListElement
{
latitude: -28.6
longitude: 25.7
}
}

...

Map {
id: map
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(-28.2, 25.3)
zoomLevel: 8
function asList() {
var list = []
for(var i = 0; i < myListModel.count; ++i) {
list.push(
        {
latitude: myListModel.get(i).latitude,
longitude: myListModel.get(i).longitude
}
);
}
return list
}
        MapPolyline
        {
    id: assetsPolyline
            line.color: "blue"
            line.width: 3
            visible : true
            path : map.asList()
        }
}

No comments:

Post a Comment