An angel on a grave stone
A young angel guarding on a grave stone in the Hietalahti Cemetery, Helsinki, Finland

Quick ternary use for data binding

Recently I have started to use a lot (alot?) more the ternary operation with the growing amount of QML I write on daily basis.

It provides an easy shortcut while defining the values of properties for an example. In order to have an actual code example, below is a snippet of a ListModel which has consistently the _name _property, but only in the last one the other property.

ListModel {
    id: itemModel
    ListElement {
        name: "Apple"
    }
    ListElement {
        name: "Fig"
    }
    ListElement {
        name: "Orange"
    }
    ListElement {
        name: "Banana"
        other: "Potato"
    }
    // Only the last item has the value for "other"...
}

The delegate which is presenting each of the ListElements will now have to take care of checking that the property does exist.

Component {
    id: itemDelegate
    Rectangle {
        Text {
            anchors.centerIn: parent
            color: "white"
            font.bold: true
            font.pointSize: 26

            // Property value is binded to a role defined in ListModel
            text: (other ? other : name)
        }
    }
}

The _text _will have the value of _name _in all others except the last one where is will use the value of other.

These two QML elements, model and delegate, could be used with ListView, GridView and PathView, non exclusively. Below a simple example of how ListView could be set.

ListView {
    id: itemList
    anchors.fill: parent
    anchors.margins: 20
    spacing: 4
    clip: true

    model: itemModel

    delegate: itemDelegate
}

See where ternary was used?