Search code examples
qtqmlmapsqqmlcomponent

How to change colour of delegate component on map in qt qml


I am using MapQuickItem as a delegate component on map. I have three component. I want to chnage the colour of delegate component when I am clicking on component.And rest are as same colour.How to change the colour of only selected component colour

 Plugin
{
    id: hereMaps
    name: "here"
    PluginParameter { name: "here.app_id"; value: "oBB4FivcP23m2UZQCj8K" }
    PluginParameter { name: "here.token"; value: "P-D8XRRGeVt0YphUuOImeA" }
}

Map {
    id: map
    anchors.fill: parent
    activeMapType: supportedMapTypes[1];
    zoomLevel: 18
    plugin: hereMaps
    center: QtPositioning.coordinate(19.997454, 73.789803)

    MapItemView {
        id: markerItem
        model: [
            { id: "marker1", color: "red" },
            { id: "marker2", color: "red" },
            { id: "marker3", color: "red" }
        ]
        delegate: mapMarkerComponent
    }

    Component {
        id : mapMarkerComponent

        MapQuickItem {
            id: mapMarker
            coordinate: QtPositioning.coordinate(19.997454, 73.789803)

            sourceItem: Rectangle {

                id: handle
                color: modelData.color
                width: 40
                height: 40

                MouseArea {
                    drag.target: parent
                    anchors.fill: parent
                    onClicked: {

                        handle.color = "green"

                    }
                }
            }

            onCoordinateChanged: {
                console.log(modelData.id + ":" + coordinate);
            }
        }
    }
   }

Solution

  • Most obvious approach is to iterate through all markers and reset colours of those, then change colour of clicked marker. To do this, change onClicked to:

    // switch to red if its green
    if (handle.color == "#008000") {
        handle.color = "#ff0000";
        return;
    }
    // switch all markers to red
    for(var marker in markerItem.children) {
        markerItem.children[marker].sourceItem.color = "#ff0000";
    }
    // switch clicked marker to green
    handle.color = "#008000";
    

    However, this is not the best solution (manipulate on colours), if you want to "select" marker. Read about states in QML (link), and try to implement some kind of "normal" and "selected" state to your markers.