Loader可以提供动态加载组件,延时实例化组件的功能。当一个应用程序组件和场景众多的时候,不可避免的要使用Loader进行动态加载,而不是刚一开始就把所有组件实例出来。-----------main.qml------------------import QtQuick 2.0Item { width: 200; height: 200 Loader { id: pageLoader } MouseArea { anchors.fill: parent onClicked: pageLoader.source = "Page1.qml" }}-------------Page1.qml---------------------import QtQuick 2.0Rectangle { width: 100 height: 100 color: "#cccccc"}Loader Sizing behaviorLoader 也有定义显示大小的时候, 如果没有知道显示大小, 那么按照qml组件的大小进行显示如果有指示大小, 那么按照指定的大小进行布局。import QtQuick 2.0Item { width: 200; height: 200 Loader { // Explicitly set the size of the Loader to the parent item's size anchors.fill: parent sourceComponent: rect } Component { id: rect Rectangle { width: 50 height: 50 color: "red" } }}--------------------------------------------------接收loader组件的信号Receiving signals from loaded objectsapplication.qmlimport QtQuick 2.0Item { width: 100; height: 100 Loader { id: myLoader source: "MyItem.qml" } Connections { target: myLoader.item onMessage: console.log(msg) }}MyItem.qmlimport QtQuick 2.0Rectangle { id: myItem signal message(string msg) width: 100; height: 100 MouseArea { anchors.fill: parent onClicked: myItem.message("clicked!") }}--------------------------------------------------对于加载的(loader)组件的焦点focus和Keys event。Item { width: 400 height: 400 Component { id: myComponent Text { text: index } //fails } ListView { anchors.fill: parent model: 5 delegate: Component { id: delegateComponent Loader { sourceComponent: myComponent } } }} delegate: Component { Loader { sourceComponent: Component { Text { text: index } //okay } } } delegate: Component { Loader { source: "MyComponent.qml" //okay } }-------------异步加载Loader { source: "mycomponent.qml" asynchronous: true visible: status == Loader.Ready}import QtQuick 2.0Item { width: 800 height: 600 Loader { id: squareLoader x:100 onLoaded: console.log(squareLoader.item.width); // prints [10], not [30] } Component.onCompleted: { squareLoader.setSource("ExampleComponent.qml", { "color": "blue" }); // will trigger the onLoaded code when complete. }}--------------------------------------------------------------------------------------import QtQuick 2.0Rectangle { id: rect color: "red" width: 300 height: 300 Behavior on color { NumberAnimation { target: rect property: "width" to: (rect.width + 20) duration: 0 } }}
Item {
width: 800
height: 600
property bool isMainPage : true
Loader {
anchors.fill: parent
id: pageLoader
}
MouseArea {
anchors.fill: parent
onClicked: {
if (isMainPage) {
pageLoader.source = "main.qml"
}else{
pageLoader.source = "AppMainWindow.qml"
}
isMainPage = !isMainPage;
}
}
}