覆盖在QML文件中设置的ListModel

时间:2014-12-03 14:43:19

标签: c++ qml qabstractlistmodel

我有一个QML C ++项目,其中C ++ Part连接后端和QML用户界面之间的连接。

我将QObject的子类设置为上下文属性,该子类具有QAbstractListModel属性。

我的一个组件在qml文件中预定义了一个List模型。我想用我自己的列表模型替换它。但是如果没有设置context属性,我想保留该模型。这允许我在没有c ++部分的情况下运行程序。 将模型设置为上下文属性没有进行剪切,因为本地模型覆盖了上下文属性。

我的QML看起来像那样

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
    }
}
}

是否可以在qml文件中同时使用Model,以便在Designer和Gui测试中显示默认值,如果我将myObject设置为上下文属性,则可以无痛地覆盖?

编辑:我在QtQuick 1.1中使用QT 4

1 个答案:

答案 0 :(得分:3)

我不知道这是否适用于QtQuick 1,但您可以依赖异常处理。这样的东西适用于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
        }
    }
}