9.qml-property自定义属性

时间:2021-04-08 13:25:36   收藏:0   阅读:0

1.property介绍

示例如下所示:

Window{
    visible: true
    property int cnt             // 未初始化,cnt默认为0
    property string label: "cnt" // 进行初始化 label = "cnt"
    
    Component.onCompleted: {
        console.log(label+","+cnt);
        cnt++;
        label = "count";
    }
    
    onLabelChanged: {
        console.log("onLabelChanged:"+label)
    }
    onCntChanged: {
        console.log("onCntChanged:"+cnt)
    }
}

运行打印:

qml: cnt,0
qml: onCntChanged:1
qml: onLabelChanged:count

 

2.基本类型数组属性自定义
基本类型数组属性自定义,则使用var泛型类型即可,示例如下所示:

Window{
    visible: true
    property var strList : [
        "str1",
        "str2",
        "str3"
    ]
    
    Component.onCompleted: {
        console.log(strList.length);
        for(var index in strList) {
            console.log(index+": "+strList[index])
        }
    }
}

 

3. QML对象数组属性自定义
如果自定义一组对象数组,则使用list<Object>类型,示例如下所示:

Window{
    visible: true
    property list<Rectangle> rectList : [
        Rectangle{ id: list1; color:"#FF0000" },
        Rectangle{ id: list2; color:"#FFFF00"},
        Rectangle{ id: list3; color:"#FFFFFF"}
    ]
    
    Component.onCompleted: {
        console.log(rectList.length);
        for(var index in rectList) {
            console.log(index+": "+rectList[index].color)
        }
    }
}

如果用var去存储QML对象数组,将会报错,因为var类型接受的array数组只能是基本类型,而Rectangle是个对象.

4.只读属性自定义
只读属性必须初始化,且不能修改,只需要在property前面加上readonly即可.
比如:

readonly property string type: "readonly"

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!