Overwrite ListModel set in QML file

832 views Asked by At

I have a QML C++ Project where the C++ Part ties the connection between a backend and the QML user interface.

I set an subclass of QObject, which has an QAbstractListModel property, as context property.

One of my components has a List model predefined in the qml file. And i would like to replace that with my own list model. But i want to keep that model if the context property is not set. That allows me to run the Program without the c++ part. Setting the model as context property didn't do the cut, because the local Model overuled the context property.

My QML looks like that

Rectangle {
id: root_rect
objectName: "root_rect"
width: 300
height: 300
color: "#dbdbdb"

ListModel {
                id: myModel
                ListElement {
                    name: "foo1"
                    fin: "bar1"
                }

                ListElement {
                    name: "foo2"
                    fin: "bar2"
                }
            }

Rectangle {
    id: list_bg
    color: "#ffffff"
    clip: true
    anchors.top: parent.top
    anchors.topMargin: 10
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 10
    anchors.left: parent.left
    anchors.leftMargin: 10
    anchors.right: parent.right
    anchors.rightMargin: 10

    ListView {
        id: list_view1
        anchors.fill: parent
        delegate: Item {
            x: 5
            height: 40
            Row {
                id: row1
                spacing: 10

                Text {
                    text: name+" "+fin
                    anchors.verticalCenter: parent.verticalCenter
                    font.bold: true
                }
            }
        }
        model: myModel
      //model: myObject.myModel
    }
}
}

Is it possible to have both, Model in qml File for display of default values in Designer and for Gui testing, and pain free overwriting if i set that myObject as context property?

Edit: i use QT 4 with QtQuick 1.1

1

There are 1 answers

1
Yoann Quenach de Quivillic On BEST ANSWER

I don't know if this work with QtQuick 1, but you could rely on exceptions handling. Something like this works with QtQuick 2:

ListView {
    id: list_view1
    anchors.fill: parent
    delegate: Item {
        ...
    }
    model: myModel
    Component.onCompleted:{
        try{
            model = myObject.myModel
        }
        catch(exception){
            console.log("myObject unknown, switching to default model")
            model = myModel
        }
    }
}