前言
Conponent :一个Component 里面只能有一个子元素, 并且Component里面的元素并不会像Rectangle一样被自动加载,需要使用loader手动加载,Component有两个信号completed() 和 destruction() 分别是当控件被加载时触发和控件被销毁时促发,类似于构造函数和析构函数
Loader:使用sourceComponent属性加载Component,将asynchronous属性设置成true可以开启异步加载、
直接看代码:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
width: 640
height: 480
visible: true // 是否可见
title: qsTr("Hello World")
Component.onCompleted: { // 当控件被创建时触发,类似与c++的构造函数
console.debug("onCompleted")
}
Component.onDestruction: { // 当控件被销毁时触发,类似与c++的析构函数
console.debug("onDestruction")
}
Component {
/* 使用Component控件时,不会像使用其他控件一样自动加载里面的元素,
需要使用loader加载
*/
id: com1
Rectangle {
id: rect1
width: 100; height:100;
color: "yellow"
}
}
Component {
id: com2
Image { // 图片
id: img1
x:300
width: 300
height: 200
source: "/images/background1.jpeg"
}
}
Component {
id: com3
AnimatedImage { // 动图
id: gif1
x:200; y:200
width: 200; height: 200
source: "/images/R-C.gif"
}
}
Loader {
id: loader
source: "main.qml" // 加载文件
sourceComponent: com3 // 加载Component控件,设置为空时,不加载
asynchronous: true // 异步加载
onStatusChanged: { // 当加载状态改变时,一共四种状态
/*
Loader.Null - the loader is inactive or no QML source has been set:0 ()
Loader.Ready - the QML source has been loaded:1 (加载完成)
Loader.Loading - the QML source is currently being loaded:2 (加载中)
Loader.Error - an error occurred while loading the QML sourc:3 (加载失败)
*/
console.debug("StatusChanged: ", status) // 加载状态
}
}
Button {
id: btn1
x: 200
onClicked: {
loader.item.color = "blue" // 对于加载的 Component 控件,需要使用 item,不能直接使用id
}
}
}