QML属性绑定

来源:互联网 发布:李小璐遭网络诈骗 编辑:程序博客网 时间:2024/05/19 20:41

所谓属性绑定,就是建立目标对象对其它对象的依赖关系,当其它对象发生变化时,目标对象也会变化,自动更新相关的属性值,达到动态属性的效果,这也是QML很重要的一个机制,先举一个简单的例子:

import QtQuick 2.3Rectangle {    width: 360; height: 200    color: "yellow"    Rectangle {        width: 100        height: parent.height        color: "red"    }    MouseArea {        anchors.fill: parent        onClicked: parent.height += 10    }}

上述例子中,红色Rectangleheight属性绑定到了黄色Rectangleheight属性上,当点击鼠标左键时,黄色Rectangleheight会递增10,这时红色Rectangleheight也会做相应的改变,这就是属性绑定中一个最简单的例子。

属性绑定的形式是多种多样的,大都是一些JavaScript表达式,在前面的例子中增加一些代码,如下:

import QtQuick 2.3Rectangle {    width: 360; height: 200    color: "yellow"    function heightIs() {        return parent.height < 250 ? parent.height : parent.height/2    }    Rectangle {        width: 100        height: parent.height//        height: parent.height / 2 + 100//        height: Math.min(parent.width, parent.height)//        height: parent.height < 250 ? parent.height : parent.height/2//        height: {//            if (parent.height < 250)//                return parent.height//            else//                return parent.height / 2//        }//        height: {//            if (parent.height < 250)//                parent.height//            else//                parent.height / 2//        }//        height: heightIs()        color: "red"    }    MouseArea {        anchors.fill: parent        onClicked: parent.height += 10    }}

上面的代码列举了属性绑定的几种形式,其中if-else的代码块中的return关键字是可写可不写的。有一点需要注意的是,如果属性绑定已经完成,那么在别的地方重新给这个属性赋值时,不管是赋个静态值,还是想换个别的属性绑定表达式,都会破坏原来的绑定关系,而新的值也不会有动态属性的效果,如下面的例子:

import QtQuick 2.3Rectangle {    width: 360; height: 200    color: "yellow"    focus: true    Keys.onSpacePressed: rect.height = parent.height – 50    // Keys.onSpacePressed: rect.height = Qt.binding(function() { return parent.height - 50 })    Rectangle {        id: rect        width: 100        height: parent.height        color: "red"    }    MouseArea {        anchors.fill: parent        onPressed: parent.height += 10    }}

红色Rectangleheight初始化时绑定到了黄色Rectangleheight上,是个动态属性,当点击鼠标左键时,黄色Rectangleheight会递增10,这时红色Rectangleheight也会做相应的改变,但是当按下空格键时,红色Rectangleheight绑定关系就被破坏了,其值只是比当前的黄色Rectangleheight50,并不会动态改变,如果想有动态属性效果的话,要使用Qt.binding(function),函数参数是一个函数,如上面例子注释掉的部分。

另外,在属性绑定时还可以使用this关键字,如下面的例子:

import QtQuick 2.3Rectangle {    width: 360; height: 360    color: "yellow"//    Component.onCompleted: rect.height = Qt.binding(function() { return width / 2 }) // 180    Component.onCompleted: rect.height = Qt.binding(function() { return this.width / 2 }) // 50    Rectangle {        id: rect        width: 100        color: "red"    }}

可以看出,this关键字指向的是接收Qt.binding(function)的返回值的对象。


1 0
原创粉丝点击