QML 属性绑定

简单的属性绑定我就不在此赘述了……这里主要看属性绑定中的在几种情况。
尊重原创:QML 静态值与属性绑定

从 JavaScript 创建属性绑定

具有绑定的属性将根据需要自动更新,但是,如果稍后从 JavaScript 语句为该属性重新分配一个静态值,则将会移除绑定。

import QtQuick 2.3

Rectangle {
    width: 200
    height: 200

    Rectangle {
        id: rect
        width: parent.width / 4
        height: 50
        color: "blue"

        focus: true
        Keys.onSpacePressed: {
            width = parent.width / 2
        }
    }
}

但是,如果是为了给 width 和其 parent 的 width 建立一个新的关系,那么新的绑定表达式必须被包裹在 Qt.binding() 函数中:

//...
Keys.onSpacePressed: {
    width = Qt.binding(function() { return parent.width / 2 })
}
//...

在属性绑定中使用 this

当从 JavaScript 创建一个属性绑定时,this 关键字可用于引用接收绑定的对象,这有助于解决属性名称产生的歧义。

例如,下面的 Component.onCompleted 处理程序在 Item 的范围内定义。此范围内,width 是指 Item 的 width,而不是 Rectangle 的 width。要将 Rectangle 的 height 绑定到其自身的 width,绑定表达式必须显式地引用 this.width(或者 rect.width):

import QtQuick 2.3

Item {
    width: 200
    height: 200

    Rectangle {
        id: rect
        width: 100
        color: "blue"
    }

    Component.onCompleted: {
        rect.height = Qt.binding(function() { return this.width * 2 })
        console.log("rect.height = " + rect.height) // 打印 200, 而非 400
    }
}
发布了32 篇原创文章 · 获赞 4 · 访问量 3414

猜你喜欢

转载自blog.csdn.net/qq_35241071/article/details/102611807
QML