一、Binding详解
1、介绍
- QML Binding是一种声明式的编程概念,它允许在Qt Quick应用中自动更新属性之间的关系。通过使用Binding,我们可以在属性之间建立依赖关系,当其中一个属性的值发生变化时,绑定的属性会自动更新。
- QML Binding使用JavaScript表达式来定义属性之间的关系。这些表达式可以包括算术运算、逻辑运算、字符串连接等操作。当定义了一个Binding后,QML会自动追踪相关的属性,并在需要的时候自动进行计算和更新。
- 可以用于任何属性,包括QML元素的属性、JavaScript对象的属性和信号的参数。通过使用Binding,开发者可以方便地处理复杂的依赖关系,减少手动更新属性的工作量。
除了基本的Binding语法外,QML还提供了一些高级的Binding技巧,如使用Binding模式来控制属性的更新频率、使用Binding动画来实现平滑的属性过渡等。 - 总的来说,QML Binding是一种强大的工具,它使开发者能够轻松实现属性之间的关系,提高应用的可维护性和灵活性。
2、相关属性
delayed : bool: 此属性决定是否应延迟绑定
property : string: 要更新的属性。
restoreMode : enumeration: 此属性可用于描述禁用绑定时是否以及如何恢复原始值。
target : QtObject: 要更新的对象。
value : var: 要在目标对象和属性上设置的值。这可以是常量(不是很有用),也可以是绑定表达式。
when : bool: 当绑定处于活动状态时,此属性保持不变。当您希望绑定处于活动状态时,应将其设置为计算结果为true的表达式。
3、使用实例
import QtQuick
import QtQuick.Controls
import Qt.labs.qmlmodels
import QtQuick.Controls.Basic
import QtQuick.Layouts
import QtQuick.Effects
import Qt.labs.platform
ApplicationWindow {
id:root
width: 1000
height: 730
visible: true
title: qsTr("Hello World")
Rectangle{
id:rect
anchors.centerIn: parent
width: 200
height: 100
color:"red"
MouseArea{
anchors.fill: parent
onClicked: {
rect.width = rect.width===200?100:200
}
}
}
Binding{
target: rect
property: "height"
value: rect.width/2
when:true
}
}
二、Qt.binding详解
返回一个表示属性绑定的JavaScript对象,该对象具有一个计算绑定的函数。
该函数有两个主要用例:首先,从JavaScript代码中强制应用属性绑定。其次,在初始化动态构造对象的属性值时应用属性绑定(通过Component.createObject()或Loader.setSource())。
使用实例:
源码:
import QtQuick
import QtQuick.Controls
import Qt.labs.qmlmodels
import QtQuick.Controls.Basic
import QtQuick.Layouts
import QtQuick.Effects
import Qt.labs.platform
ApplicationWindow {
id:root
width: 1000
height: 730
visible: true
title: qsTr("Hello World")
property int edgePosition: 0
Rectangle{
id:rect
anchors.centerIn: parent
width: 200
height: width/2
color:"red"
MouseArea{
anchors.fill: parent
onClicked: {
rect.width = rect.width===200?150:200
console.log(edgePosition)
}
}
Text {
anchors.fill: parent
font.pointSize: 20
text: edgePosition
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
Component.onCompleted: {
edgePosition = Qt.binding(function(){
return rect.x+rect.width
})
}
}
}
当Rectangle创建完成后绑定edgePosition
变量为Rectangle
的x
加上宽度width
,当Rectangle
的x
或width
发生变化时edgePosition
就会自动更新。