QQuick-Binding的介绍
QQuick-Binding的介绍
Binding的概述
-
属性绑定:在qml中两个对象的属性和属性之间可以形成依赖,直接属性绑定 如 width: parent.width; 即 对象宽度 与父对象的宽度进行绑定;除了默认的属性绑定,还可以通过Bingding对象建立显示的属性绑定
-
Binding 用于对象之间的属性绑定;即可以用于 直接的属性绑定; 也可以用于满足条件的属性绑定,即绑定的目标需在满足条件时才会使用绑定的属性值。
-
属性property : string:要绑定的属性名称,即要更新的属性
-
属性target : QtObject:要绑定的对象,即要更新的对象
-
属性value : var: 给绑定对象的属性要设置的值
-
属性when : bool: 绑定生效的判断条件,当值为true 时,绑定才生效。
Binding的实例代码
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
//属性绑定:在qml中两个对象的属性和属性之间可以形成依赖,直接属性绑定 如 width: parent.width; 即 对象宽度 与父对象的宽度进行绑定
//除了默认的属性绑定,还可以通过Bingding对象建立显示的属性绑定
//Binding 用于对象之间的属性绑定; 即可以用于 直接的属性绑定,也可以用于满足条件的修改属性值,不满足条件保持原值
Item {
id: idTabBarRoot
Rectangle{
id:rec1
x:0
y:0
width: 100
color: "red"
height: 40
PropertyAnimation{
id: ana
target: rec1
duration: 2000
running: false
loops: 1
property: "width"
from:100
to:200
onRunningChanged: {
console.log("running changed",running);
}
}
MouseArea{
anchors.fill: parent
onClicked: {
console.log("clicked");
ana.running = true;
}
}
}
Rectangle{
id: rec2
y:50
width: rec1.width //隐形的属性绑定,即 rec2.width 跟随 rec1.width 变化
color:"blue"
height: 40
}
Rectangle{
id: rec3
y:100
color:"green"
height: 40
width: 100
// Binding{
// rec3.width: rec1.width
// }
//显示指明一个绑定
Binding{
target: rec3
property: "width"
value: rec1.width;
when: rec1.width > 150 //当满足条件时,value 才与 rec1.width值进行绑定
}
}
Rectangle{
id: rec4
y:150
color:"yellow"
height: 40
width: 100
//当鼠标释放,值为200
Binding on width{
when:mouse1.pressed //当鼠标按下,宽度变为200
value: 200
}
MouseArea{
id:mouse1
anchors.fill: parent
}
}
}