一、概念
Component是由Qt框架封装好的,只暴露了必要接口的QML类型,可以重复使用。一个QML组件就像一个黑盒子,它通过属性、信号、函数和外部世界交互。
一个Component既可以定义在单独的QML文件中,也可以嵌入到其他的QML文档中来定义。
嵌入式定义组件
import QtQuick 2.2
Rectangle {
width: 320;
height: 240;
color: "#C0C0C0";
......
Component {
id: colorComponent;
Rectangle {
id: colorPicker;
width: 50;
height: 30;
signal colorPicked(color clr);
MouseArea {
anchors.fill: parent;
onPressed: colorPicker.colorPicked(colorPicker.color);
}
}
}
......
}
- Component只能包含一个顶层Item(本例中是Rectangle),而且在这个Item之外不能定义任何数据,除了id;
- 在顶层Item之内,则可以包含更多的子元素来协同工作,最终形成一个具有特定功能的组件;
在单独文件中定义组件
//ColorPicker.qml
import QtQuick 2.2
Rectangle {
id: colorPicker;
width: 50;
height: 30;
signal colorPicked(color clr);
function configureBorder() { //设置边框的宽度和颜色
colorPicker.border.width = colorPicker.focus ? 2 : 0;
colorPicker.border.color = colorPicker.focus ? "#90D750" : "#808080";
}
MouseArea {
anchors.fill: parent;
onClicked: {
colorPicker.colorPicked(colorPicker.color);
mouse.accepted = true;
colorPicker.focus = true;
}
}
Keys.onReturnPressed: {
colorPicker.colorPicked(colorPicker.color);
event.accepted = true;
}
Keys.onSpacePressed: {
colorPicker.colorPicked(colorPicker.color);
event.accepted = true;
}
onFocusChanged: {
configureBorder();
}
Component.onCompleted: {
configureBorder();
}
}
单独文件中定义组件与嵌入式定义组件代码结构明显不同:Component对象不见了! 在单独文件定义组件,不需要Component对象,只有在其它QML文档中嵌入式定义组件时才需要Component对象; 注意:定义Component组件时需要遵守一个约定:组件名必须和QML文件名一致,首字母必须大写;
单独文件定义组件的使用
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
Rectangle {
width: 320;
height: 240;
color: "#EEEEEE";
Text {
id: coloredText;
anchors.horizontalCenter: parent.horizontalCenter;
anchors.top: parent.top;
anchors.topMargin: 4;
text: qsTr("Hello World!");
font.pixelSize: 32;
}
function setTextColor(clr) {
coloredText.color = clr;
}
ColorPicker {
id: redColor;
color: "red";
focus: true;
anchors.left: parent.left;
anchors.leftMargin: 4;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
KeyNavigation.right: blueColor;
KeyNavigation.tab: blueColor;
onColorPicked: {
coloredText.color = clr;
}
}
ColorPicker {
id: blueColor;
color: "blue";
anchors.left: redColor.right;
anchors.leftMargin: 4;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
KeyNavigation.left: redColor;
KeyNavigation.right: pinkColor;
KeyNavigation.tab: pinkColor;
}
ColorPicker {
id: pinkColor;
color: "pink";
anchors.left: blueColor.right;
anchors.leftMargin: 4;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
KeyNavigation.left: blueColor;
KeyNavigation.tab: redColor;
onColorPicked: {
coloredText.color = clr;
}
}
Component.onCompleted: {
blueColor.colorPicked.connect(setTextColor);
pinkColor.colorPicked.connect(setTextColor);
}
}
}
|