在這篇文章中。我們將介紹怎樣使用Loader來載入不同的QML文件來實現動態的UI。在之前的文章“怎樣使用Loader來動態載入一個基於item的Component”中,我們已經介紹了一些關於它的使用方法。
Loader的優點是僅僅有在我們須要的時候才裝載我們所須要的QML文件,這樣能夠節省應用所須要的內存,也同一時候能夠提高應用的啟動時間(假設利用好的話)。以下我們以一個簡單的樣例來做一個介紹。很多其它關於動態生產QML UI的樣例,請參閱“怎樣使用QML動態產生Component來完畢我們的氣球游戲(2)”。
MainScreen.qml
import QtQuick 2.0
Rectangle {
id: root
width: 600
height: 400
property int speed: 0
SequentialAnimation {
running: true
loops: Animation.Infinite
NumberAnimation { target: root; property: "speed"; to: 145; easing.type: Easing.InOutQuad; duration: 4000; }
NumberAnimation { target: root; property: "speed"; to: 10; easing.type: Easing.InOutQuad; duration: 2000; }
}
// M1>>
Loader {
id: dialLoader
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: analogButton.top
onLoaded: {
binder.target = dialLoader.item;
}
}
Binding {
id: binder
property: "speed"
value: speed
}
// <<M1
Rectangle {
id: analogButton
anchors.left: parent.left
anchors.bottom: parent.bottom
color: "gray"
width: parent.width/2
height: 100
Text {
anchors.centerIn: parent
text: "Analog"
}
MouseArea {
anchors.fill: parent
onClicked: root.state = "analog";
}
}
Rectangle {
id: digitalButton
anchors.right: parent.right
anchors.bottom: parent.bottom
color: "gray"
width: parent.width/2
height: 100
Text {
anchors.centerIn: parent
text: "Digital"
}
MouseArea {
anchors.fill: parent
onClicked: root.state = "digital";
}
}
state: "analog"
// M3>>
states: [
State {
name: "analog"
PropertyChanges { target: analogButton; color: "green"; }
PropertyChanges { target: dialLoader; source: "Analog.qml"; }
},
State {
name: "digital"
PropertyChanges { target: digitalButton; color: "green"; }
PropertyChanges { target: dialLoader; source: "Digital.qml"; }
}
]
// <<M3
}
Loader {
id: dialLoader
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: analogButton.top
onLoaded: {
binder.target = dialLoader.item;
}
}
它的source沒有被指定。
在程序中。它是能夠被動態設置的。從而達到改變UI的目的。另外我們要注意到“dialLoader.item”,它實際上是在QML被裝載完后最頂層的那個Item。對我們來說。當Analog.qml被裝載后,這個Item就是Ananlog.qml所代表的Item。
每當Loader的source發生改變時,它先前創建的Item將會被自己主動地銷毀。
在程序中,也設置了兩個Rectangle,被用作button的用途。點擊它時,能夠改變當前Component的state,從而裝載不同的qml,以達到改變UI的目的。
在應用中。默認的狀態是“analog”。而不是我們通常的“”狀態。
在我們的手機上執行:
