QML动态加载组件

QML中的组件可以重复使用,并且可以通过Loader加载。如下示例:

 1 import QtQuick 2.4
 2 import QtQuick.Controls 1.3
 3 import QtQuick.Window 2.2
 4 import QtQuick.Dialogs 1.2
 5 
 6 Rectangle{
 7     id: root
 8       512
 9     height: 512
10     color: "gray"
11 
12     Text {
13         id: coloredText
14         anchors.horizontalCenter: parent.horizontalCenter
15         anchors.top: parent.top
16         anchors.topMargin: 20
17 
18         text: "Hello World"
19         color: "blue"
20         font.pointSize: 30
21     }
22 
23     Component {
24         id: colorComponent
25         Rectangle {
26             id: colorPicker
27              50
28             height: 30
29 
30             signal colorPicked(color clr);
31 
32             MouseArea {
33                 anchors.fill: parent
34                 onPressed: colorPicker.colorPicked(colorPicker.color);
35             }
36         }
37     }
38 
39     Loader {
40         id: redLoader
41         anchors.left: parent.left
42         anchors.leftMargin: 4
43         anchors.bottom: parent.bottom
44         anchors.bottomMargin: 4
45 
46         sourceComponent: colorComponent
47         onLoaded: {
48             item.color = "red"
49         }
50     }
51 
52     Loader {
53         id: blueLoader
54         anchors.left: redLoader.right
55         anchors.leftMargin: 4
56         anchors.bottom: parent.bottom
57         anchors.bottomMargin: 4
58 
59         sourceComponent: colorComponent
60         onLoaded: {
61             item.color = "blue"
62         }
63     }
64 
65     Connections {
66         target: redLoader.item
67         onColorPicked: {
68             coloredText.color = clr
69         }
70     }
71 
72     Connections {
73         target: blueLoader.item
74         onColorPicked: {
75             coloredText.color = clr
76         }
77     }
78 }
原文地址:https://www.cnblogs.com/xiaomanon/p/4546285.html