main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
Window {
width: 640
height: 480
color: "white"
title: qsTr("My QML")
visible: true
Component{
id:com
//动态传入组件
//加载方式1
Button{
width: 50
height: 50
}
//加载方式2
// Rectangle{
// width: 50
// height: 50
// color: "yellow"
// }
}
MyRectangle{
myComponent: com
myTopMargin: 10
//Item构造
Component.onCompleted: {
//赋值失败,myValue是readonly
// myValue=21
//通过别名修改控件属性
newInnerRect.color="red"
console.log(myValue)
}
}
}
MyRectangle.qml
import QtQuick 2.0
Rectangle {
id:borderRect
width: 100
height: 100
color: "black"
property int myTopMargin: 0
property int myBottomMargin: 0
//整型
readonly property int myValue: 0
//浮点型
property real myReal: 0.0
//字符串
property string myString: "test"
//URL字符串
property url myUrl: "qrc:/test.jpg"
//Item
property Component myComponent
//auto
property var myVar: "0.0"
//array
property list<Rectangle> myList
//别名
property alias newInnerRect: innerRect
Rectangle{
id:innerRect
color: "blue"
anchors.fill: parent
anchors.topMargin: myTopMargin
anchors.bottomMargin: myBottomMargin
anchors.leftMargin: 0
anchors.rightMargin: 0
Loader{
id:loader
sourceComponent: myComponent
}
}
}