qt 之 qml 类型 Binding
文章目錄
- Binding 使用場(chǎng)景
- 一、Binding
- 二、使用步驟
- 1.綁定到無(wú)法訪(fǎng)問(wèn)的屬性:
- 2.綁定Item property:
- 3.根據(jù)條件綁定到單分支。
Binding 使用場(chǎng)景
有時(shí)候,我們需要綁定一個(gè)不是QML直接實(shí)例化的組件的屬性。一般是一個(gè)C++擴(kuò)展的屬性。或者這樣的場(chǎng)景下,條件判斷比如
value: if (mouse.pressed) mouse.mouseX在這種情況下,一般的綁定不工作,而 Binding類(lèi)型則允許我們綁定任何值到任何屬性上。
一、Binding
| property | string | 被更新的屬性 |
| target | Object | 被更新的目標(biāo) |
| delayed | bool | 延遲綁定不會(huì)立即更新目標(biāo),而是等到事件隊(duì)列已被清除。這可以作為一個(gè)優(yōu)化,或防止中介值被分配 |
| value | any | 要在目標(biāo)對(duì)象和屬性上設(shè)置的值,它能是一個(gè)常數(shù)(不常用),或者綁定的表達(dá)式 |
| when | bool | 綁定是否被激活,它應(yīng)該被設(shè)置成表達(dá)式,用以判斷我們是否想激活綁定 |
| restoreMode | enumeration | 當(dāng)綁定條件不符合時(shí),描述當(dāng)且時(shí)應(yīng)該如何恢復(fù)原始值 |
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.綁定到無(wú)法訪(fǎng)問(wèn)的屬性:
有時(shí)候,我們需要綁定一個(gè)不是QML直接實(shí)例化的組件的屬性。一般是一個(gè)C++擴(kuò)展的屬性。在這種情況下,一般的綁定不工作,Binding允許我們綁定任何值到任何屬性上。
例如,一個(gè)C++應(yīng)用程序影射了一個(gè)叫app.enteredText的屬性到QML,我們可以用Binding屬性來(lái)更新app.enteredText,就像下面的例子這樣:
TextEdit { id: myTextField; text: "Please typehere..." }Binding { target: app; property: "enteredText";value: myTextField.text }當(dāng)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.根據(jù)條件綁定到單分支。
有時(shí)候,我們希望當(dāng)某些條件為真時(shí),屬性的值能被控制。而所有其他情況下,我們放棄對(duì)屬性的控制。這時(shí)候,直接完成綁定是不可能的,因?yàn)檫@需要為所有可能的分支提供值。
例如:
// produces warning: "Unable to assign [undefined]to double value" value: if (mouse.pressed) mouse.mouseX在上面的例子中,無(wú)論什么時(shí)候釋放鼠標(biāo),警告都會(huì)發(fā)生。因?yàn)楫?dāng)鼠標(biāo)沒(méi)有被按下時(shí),value沒(méi)有定義。注意,上面的屬性加冒號(hào),就是通常的綁定方法。
與之區(qū)別的,是我們使用Binding來(lái)處理這種預(yù)期,以避免警告。例如下面的代碼:
Binding on value {when:mouse.pressedvalue:mouse.mouseX }Binding組件也能恢復(fù)預(yù)先直接綁定在屬性上的值,從這個(gè)角度來(lái)說(shuō),這個(gè)組件就像是一個(gè)簡(jiǎn)化版的State。
下面的代碼等效于上面的Binding:
State {name:"pressed"when:mouse.pressedPropertyChanges {target: objvalue: mouse.mouseX} }如果綁定的目標(biāo)或?qū)傩愿?#xff0c;綁定值會(huì)立刻被推送到新目標(biāo)上
總結(jié)
以上是生活随笔為你收集整理的qt 之 qml 类型 Binding的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 新手学习开源项目zheng环境部署
- 下一篇: 高考英语语法填空满分秒杀技巧