QMLBinding

一、概念

Binding用于属性绑定,这是基于QML组件式的属性绑定;QML语法绑定、JS动态绑定见:https://www.cnblogs.com/judes/p/13158840.html。

所以一般称Binding为间接绑定。

二、例子

1、为Loader绑定

使用Loader时,往往时动态加载Component或者QML的,所以在写代码时是不确定Loader的item是什么的,如果想为动态加载的组件属性绑定,使用以往的属性绑定方式是不方便或无法实现的,使用Binding则非常方便。

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3

Window {
    id: root
    visible: true
     640
    height: 480
    title: qsTr("Hello World")
    property int speed_new: 10
    Loader{
        id: l1
        anchors.centerIn: parent
         200;
        height: 200
        sourceComponent: c1
        onLoaded:{
            binder.target=l1.item;
        }
    }
    SequentialAnimation {
        running: true
        loops: Animation.Infinite

        NumberAnimation { target: root; property: "speed_new"; to: 145; easing.type: Easing.InOutQuad; duration: 4000; }
        NumberAnimation { target: root; property: "speed_new"; to: 10; easing.type: Easing.InOutQuad; duration: 2000; }
    }
    Binding{
        id:binder
        property:"speed"
        value:speed_new
    }
    Component {
        id: c1
        Rectangle {
            property int speed: 0
             100
            height: 100
            radius: width/2
            color: "red"
            Text {
                id: t
                text: speed
                anchors.centerIn: parent
            }
        }
    }
}

 这个例子是将Loader动态加载【这里其实是静态加载,如果把loader的sourceComponent写在构造函数里辨识模拟动态,这里做例子不影响】,然后将loader的item【c1】的属性speed与一个会变化的speed_new进行动态绑定。

原文地址:https://www.cnblogs.com/judes/p/15678676.html