Search code examples
qtdelegatesqmlqtlocation

Introduce condition in delegate


I seek for introduce a condition in a delegate.

Here is a simplified main.qml

import QtQuick 2.6
import QtQuick.Window 2.2
import QtPositioning 5.5
import QtLocation 5.6

Window {
    width: 1440
    height: 900
    visible: true

    property variant topLeftEurope: QtPositioning.coordinate(60.5, 0.0)
    property variant bottomRightEurope: QtPositioning.coordinate(51.0, 14.0)
    property variant boundingBox: QtPositioning.rectangle(topLeftEurope, bottomRightEurope)

    Map {
        id: mainMap
        anchors.centerIn: parent;
        anchors.fill: parent
        plugin: Plugin {name: "osm"}

        MapItemView {

            model: myModel

            delegate: Marker{}   

        }
        visibleRegion: boundingBox
    }
}

It displays the map and defines a bounding Box.

and here is the delegate : Marker.qml

import QtQuick 2.4
import QtLocation 5.6



MapQuickItem {
    id: mark

coordinate: position //"position" is roleName

    ... all the stuff for the marker to be displayed on the map
}

I wish to add this condition to discard the points which are not within the bounding box to be displayed :

if (main.boundingBox.contains(position)){
    ... display the marker on the map
}

but if is not usable directly in my code.

I've tried to add a function :

function isMarkerViewable(){
    if (!main.boundingBox.contains(position))
        return;
}

but I'm not able to call it, too.

Is it possible to add a condition in a delegate and, if yes, how to do it ?

Thanks for your help


Solution

  • As @derM comments one option is to use Loader, in the following example each point has an attribute called type that serves to distinguish which items should be drawn a rectangle or circle.

    Marker.qml

    import QtQuick 2.0
    import QtLocation 5.6
    
    MapQuickItem {
        sourceItem: Loader{
            sourceComponent:
                if(type == 0)//some condition
                    return idRect
                else if(type == 1) //another condition
                    return idCircle
    
        }
        Component{
            id: idRect
            Rectangle{
                width: 20
                height: 20
                color: "blue"
            }
        }
        Component{
            id: idCircle
            Rectangle{
                color: "red"
                width: 20
                height: 20
                radius: 50
            }
        }
    }
    

    main.qml

    MapItemView {
        model: navaidsModel
        delegate:  Marker{
            coordinate:  position
        }
    }
    

    Output:

    enter image description here

    You can find a complete example in the following link.