QML 属性绑定 (Property Binding)
属性的绑定能够更好的使用QML的特性-QML object动态行为变化的自动响应。这是QML一个很重要的特性。

注意: 绑定的一个很重要的标志就是 “:” –冒号

当QML object 的属性既可以分配一个static value,也可以绑定一个JavaScript表达式,也可以使用JavaScript的自带的Date Math这些对象。因为QML uses a standards compliant JavaScript engine。

Rectangle { 
  id: parentRect 
  width: 200; 
  height: 200 
      Rectangle { 
        id: childRect 
        width: 100; 
        height: parent.height 
        color: "blue" 
     }
}

上面的代码中,childRect的height绑定到了parent的height,当parentRect的height改变的时候,QML engine会重新计算childRect.height

import QtQuick 2.0
Rectangle { 
  width: 100 
  height: width * 2 
  focus: true 
    Keys.onSpacePressed: { 
      height = width * 3 
   }
}

在看上面的这段代码,Rectangle的height首先绑定了width 2,然后在Key.onSpacePressed这个附带的signal handler中,height 被赋值width 3, 注意 是赋值,不是绑定。

所以之前的bind被这个赋值语句移除了,也就是说以后Rectangle的width变化了,height不会自动变成width的2倍。

如果是想要重新binding而不是赋值,则需要使用Qt.binding()。

this的使用

使用JavaScript绑定时,QML允许使用Javascript中this关键字。

例如下面的代码:

Item { 
   width: 500 
   height: 500 
       Rectangle { 
         id: rect 
         width: 100 
         color: "yellow" 
       } 

Component.onCompleted: { 
     rect.height = Qt.binding(function() { 
     return this.width * 2 
}) 

   console.log("rect.height = " + rect.height) // prints 200, not 1000 
  }
} 

rect.heigth属性的绑定使用了JavaScript的语句,所以可以使用this,这里的this表示的是Item而不是rect

标签: none

文章分类

归档