Tuesday 22 May 2012

Parameterisation of dynamic QML Component

I'm putting together a QML framework for an embedded UI. One of the elements is type of ListView that contains a "radiobutton" on each line. The idea is to make the elements re-usable throughout the UI so I don't want to specify the other sub-elements in each line.

My solution is to use the Component / Loader mechanism and pass a ListElement parameter into the Component.

RadioView.qml



import QtQuick 1.0
ListView {
    // The index of the selected radiobutton or -1 for none
    property int selected: -1

    // (optional) Additional component to display in each row, modelData parameter is
    // set to row data
    property QtObject elements


    delegate: Rectangle {
        height: 20
        Loader {
            anchors.left: parent.left
            anchors.verticalCenter: parent.verticalCenter
            sourceComponent: elements
            // Pass through this row's ListElement
            onLoaded: children[0].modelData=model
        }
        Image {
            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
            source: selected==index ? "checked.png" : "unchecked.png"
            /* Mouse stuff I won't bore you with */
        }
    }
}




MyChoice.qml


import QtQuick 1.0
RadioView {
    // Display 'label'
    elements: Component {
        Text {
            // Receives ListElement from RadioView
            property QtObject modelData
            text: modelData.label
        }
    }

    model: ListModel {
        ListElement {
            label: "Choice 1"
        }
        ListElement {
            label: "Choice 2"
        }
        ListElement {
            label: "Choice 3"
        }
    }
}


No comments:

Post a Comment