qml学习--------------Component(组件)学习

来源:互联网 发布:怎么关闭cpu多线程优化 编辑:程序博客网 时间:2024/05/25 23:57

Component是Qt框架或者开发者封装好的,只暴露必要接口的QML类型,可以重复利用。一个QML组件就像是一个黑盒子,他通过属性,信号,函数和外部交互。
一个QML组件可以定义在独立的QML文件中,也可以嵌入到其他的QML文档中来定义。

嵌入式的定义组件

Component{
id: colorComponent;
Rectangle{
id: colorPicker;
width: 50;
height: 30;
signal colorPicked(color clr);
MouseArea{
anchors.fill:parent;
onPressed: colorPicker.colorPicked(colorPicker.color);
}
}

}

这样就定义了一个可以嵌入在qml内部的组件了。

下面再来看下在单独文件中定义组件

Control{
id: indicator;
property bool running: true;

Accessible.role:Accessible.Indicator;
Accessible.name:”Busy”;

style: Qt.createComponent(Setting.style +
“/BusyIndicatorStyle.qml” , indicator);

}

下面就来具体学习下组件的使用。

首先是自定义的组件

import QtQuick 2.2Rectangle{    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();    }}

然后是 自定义组件的使用

import QtQuick 2.2

Rectangle{
width: 320;
height: 240;
color: “#eeeeee”;

Text{    id: colorText;    anchors.horizontalCenter:  parent.horizontalCenter;    anchors.top : parent.top;    anchors.topMargin: 4;    text:"hello World";    font.pixelSize: 32;}function setTextColor(clr){    colorText.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: {        colorText.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;}Component.onCompleted: {    blueColor.colorPicked.connect(setTextColor);    pinkColor.colorPicked.connect(setTextColor);}

}

在里面同时还学习了关于自定义信号的连接等问题。
组件的初步学习基本就这样了

0 1