为什么需要动态加载组件?
1.在不确定加载视图A或视图B时,可以延时创建组件以达到自己想要的效果。
2.组件模块化,保证程序的阅读质量以及封装性的提高。
3.组件在不加载时,不占用内存。
文件内加载组件方式
import QtQuick 2.9
import QtQuick.Controls 2.2
ApplicationWindow {
id: windowview
visible: true
width: 640
height: 480
title: qsTr("加载组件")
Loader{ //加载组件
id: loader
anchors.centerIn: parent //组件的位置由加载器进行设置
sourceComponent: componentRectangle //加载组件
}
Component{ //组件
id: componentRectangle
Rectangle{ //组件中的对象
id: rectangleComponent
width: 100
height: 100
color: "black"
}
}
}
加载独立QML文件的方式
主视图只用loader加载文件即可,加载文件名为"MyRectangle.qml"
import QtQuick 2.9
import QtQuick.Controls 2.2
ApplicationWindow {
id: windowview
visible: true
width: 640
height: 480
title: qsTr("加载qml文件")
Loader{ //加载组件
id: loader
anchors.centerIn: parent //组件的位置由加载器进行设置
source: "MyRectangle.qml" //加载qml文件
}
}
MyRectangle.qml
import QtQuick 2.0
Rectangle{
id: rectangleComponent
width: 100
height: 100
color: "black"
}