網站搬家 備案短視頻培訓要多少學費
Qml-Item的Id生效范圍
前置聲明
- 本實例在Qt6.5版本中做的驗證
- 同一個qml文件中,id是唯一的,即不同有兩個相同id 的Item;當前qml文件中聲明的id在當前文件中有效(即如果其它組件中傳入的id,與當前qml文件中id 相同,當前qml文件中id生效)
- 在父級qml文件中聲明的id,可以傳遞給子集的qml文件中使用
- 實例由4個qml文件組成:主qml ( ItemIdScopeTest.qml): 由3個子qml組件元素;子qml1(ItemIdGDataPro.qml)定義了一個純屬性的Item,另兩個子qml(ItemIdComponent_1.qml,ItemIdComponent_2.qml)中由一個Rectangle元素組成
Item Id生效范圍 實例代碼
- ItemIdGDataPro.qml文件,定義了id名稱和兩個color屬性, 代碼如下:
import QtQuick
//由于測試Item中id 作用范圍和影響
Item{id:idGDataProproperty color reColor1: "blue"property color reColor2: "green"onReColor1Changed: {console.log("reColor___1 Changed");}onReColor2Changed: {console.log("reColor___2 Changed");}}
2.ItemIdComponent_1.qml 文件內容如下
import QtQuick
//用于測試Item中id 作用范圍和影響
Item{ItemIdGDataPro{id:idGDataProproperty color reColor1: "blue"}Rectangle{id:idComp1width: 100height: 100color: idGDataPro.reColor1}
}
3.ItemIdComponent_2.qml 文件內容如下
import QtQuick//由于測試Item中id 作用范圍和影響
Item{Rectangle{id:idComp2width: 100height: 100//Comp2 中 idGDataPro.reColor2color: idGDataPro.reColor2}
}
3.ItemIdScopeTest.qml 文件,使用其它3個 子qml 元素,內容如下
import QtQuick//由于測試Item中id 作用范圍和影響。
//1.在同一個qml中不能有Item 有相同的id;
//1.在qml文件中,定義的id 優(yōu)先級最高
//2.在父qml文件中,設置其它Item的id,包含在父qml文件中其它組件所在qml中可以使用此id的屬性Item{height: 480width: 320Rectangle{anchors.fill: parentItemIdGDataPro{id:idGDataPro}ItemIdComponent_1{id:idComp1x:20y:20}ItemIdComponent_2{id:idComp2x:150y:20}}
}
結果:
1.ItemIdScopeTest.qml 文件中定義的Id,可以在ItemIdComponent_2.qml中使用;
2.ItemIdComponent_1.qml 中定義了相同Id名稱的“ idGDataPro”,在ItemIdComponent_1.qml文件中就使用了自身定義的“idGDataPro”;
3.實驗驗證方式:可以通過添加onXXXChanged() 函數(shù)(XXX代表定義的屬性),來驗證是哪個對應屬性發(fā)生了改變
Item Id生效范圍效果
1.可驗證:
a.主qml中不定義ItemIdGDataPro 對象,,在子qml組件中使用ItemIdGDataPro 的屬性效果。
b.主qml中定義ItemIdGDataPro 對象,,在某個子qml組件中定義主qml同樣屬性Id的對象,修改主qml中ItemIdGDataPro 對象屬性值,查看是否影響子qml中屬性值。