qt 之 qml 类型 Binding
文章目錄
- Binding 使用場景
- 一、Binding
- 二、使用步驟
- 1.綁定到無法訪問的屬性:
- 2.綁定Item property:
- 3.根據條件綁定到單分支。
Binding 使用場景
有時候,我們需要綁定一個不是QML直接實例化的組件的屬性。一般是一個C++擴展的屬性。或者這樣的場景下,條件判斷比如
value: if (mouse.pressed) mouse.mouseX在這種情況下,一般的綁定不工作,而 Binding類型則允許我們綁定任何值到任何屬性上。
一、Binding
| property | string | 被更新的屬性 |
| target | Object | 被更新的目標 |
| delayed | bool | 延遲綁定不會立即更新目標,而是等到事件隊列已被清除。這可以作為一個優化,或防止中介值被分配 |
| value | any | 要在目標對象和屬性上設置的值,它能是一個常數(不常用),或者綁定的表達式 |
| when | bool | 綁定是否被激活,它應該被設置成表達式,用以判斷我們是否想激活綁定 |
| restoreMode | enumeration | 當綁定條件不符合時,描述當且時應該如何恢復原始值 |
restoreMode:
Binding.RestoreNone The original value is not restored at all
Binding.RestoreBinding The original value is restored if it was another binding. In that case the old binding is in effect again.
Binding.RestoreValue The original value is restored if it was a plain value rather than a binding.
Binding.RestoreBindingOrValue The original value is always restored.
二、使用步驟
1.綁定到無法訪問的屬性:
有時候,我們需要綁定一個不是QML直接實例化的組件的屬性。一般是一個C++擴展的屬性。在這種情況下,一般的綁定不工作,Binding允許我們綁定任何值到任何屬性上。
例如,一個C++應用程序影射了一個叫app.enteredText的屬性到QML,我們可以用Binding屬性來更新app.enteredText,就像下面的例子這樣:
TextEdit { id: myTextField; text: "Please typehere..." }Binding { target: app; property: "enteredText";value: myTextField.text }當TextEdit被更新,則C++屬性也將更新。
2.綁定Item property:
Item{id: itemproperty rect rectangle: Qt.rect(0, 0, 200, 200)}Binding {target: itemproperty: "rectangle.x"value: 100} Binding {target:contactName; property: 'text'value: name;when: list.ListView.isCurrentItem }3.根據條件綁定到單分支。
有時候,我們希望當某些條件為真時,屬性的值能被控制。而所有其他情況下,我們放棄對屬性的控制。這時候,直接完成綁定是不可能的,因為這需要為所有可能的分支提供值。
例如:
// produces warning: "Unable to assign [undefined]to double value" value: if (mouse.pressed) mouse.mouseX在上面的例子中,無論什么時候釋放鼠標,警告都會發生。因為當鼠標沒有被按下時,value沒有定義。注意,上面的屬性加冒號,就是通常的綁定方法。
與之區別的,是我們使用Binding來處理這種預期,以避免警告。例如下面的代碼:
Binding on value {when:mouse.pressedvalue:mouse.mouseX }Binding組件也能恢復預先直接綁定在屬性上的值,從這個角度來說,這個組件就像是一個簡化版的State。
下面的代碼等效于上面的Binding:
State {name:"pressed"when:mouse.pressedPropertyChanges {target: objvalue: mouse.mouseX} }如果綁定的目標或屬性更改,綁定值會立刻被推送到新目標上
總結
以上是生活随笔為你收集整理的qt 之 qml 类型 Binding的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手学习开源项目zheng环境部署
- 下一篇: 高考英语语法填空满分秒杀技巧