(五)组件与动态对象

组件

Component是封装好了的,只暴露了必要接口的QML类型,可以重复利用。
一个Component既可以定义在独立的QML文件中,也可以嵌入到其他的QML文档中,通常如果一个Component比较小并且只在某个QML文档中使用,或者一个Component从逻辑上看从属于某个QML文档,那么就可以采用嵌入的方式来定义该Component。

嵌入式定义组件

下面一个颜色选择组件代码:

 Component {
     id: colorComponent;
     Rectangle {
         id: colorPicker;
         width: 50;
         height: 30;
         signal colorPicked(color clr);  //自定义信号
         MouseArea {
             anchors.fill: parent;
             onPressed: colorPicker.colorPicked(colorPicker.color); //鼠标点击发射信号
         }
     }
 }

定义一个Component和定义一个QML文档类似,Component只能包含一个顶层Item,而且在这个Item之外除了id不能定义任何数据,例如上面的代码,顶层Item是Rectangle,在Rectangle之外定义了id属性。

在单独文件中定义组件

很多时候我们把一个Component单独定义在一个QML文档中,比如Qt Quick提供的BusyIndicator控件,其实就是在BusyIndicator.qml中定义的一个组件,下面是BusyIndicator.qml文件的内容:

Control {
    id: indicator
    property bool running: true

    Accessible.role: Accessible.Indicator
    Accessible.name: "busy"

    style: Settings.styleComponent(Settings.style, "BusyIndicatorStyle.qml", indicator)
}

可以看到,BusyIndicator.qml文件中的顶层Item是Control,而我们使用时是以BusyIndicator为组件名,这是我们定义Component时要遵守的一个约定:组件名必须和QML文件名一致,还有一点,组件名第一个字母必须是大写的。
下面看一个在单独文件中定义的ColorPicker组件:

import QtQuick 2.0

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.coloPicker(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对象。
使用ColorPicker组件:

import QtQuick 2.0

Rectangle {
    width: 320;
    height: 240;
    color: "#EEEEEE";
    Text {
        id: coloredText;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top: parent.top;
        anchors.topMargin: 4;
        text: "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;		//tab键
    }

    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);//connect连接信号槽
        pinkColor.colorPicked.connect(setTextColor);
    }
}

注意:必须把ColorPicker.qml和component_file.qml放在同一个文件夹下,否则会报错。
对于定义在单独文件中的Component,除了上述使用方法之外,还可以使用Loader来动态加载,根据需要再创建。

Loader

Loader基本使用

Loader可以使用其soruce属性加载一个QML文档,也可以通过其sourceComponent属性加载一个Component对象。当你需要延迟一些对象直到真正需要才创建它们时,Loader非常有用。

import QtQuick 2.0

Rectangle {
    width: 320;
    height: 240;
    color: "#C0C0C0";

    Text{
        id: coloredText;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top: parent.top;
        anchors.topMargin: 4;
        text: "Hello World!";
        font.pixelSize: 32;
    }

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

    Loader{
        id: redLoader;
        width: 80;
        height: 60;
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        sourceComponent: colorComponent;
        onLoaded: {
            item.color = "red";
        }
    }

    Loader{
        id: blueLoader;
        anchors.left: redLoader.right;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        sourceComponent: colorComponent;
        onLoaded: {
            item.color = "blue";
        }
    }

    Connections{
        target: redLoader.item;
        onColorPicked:{
            coloredText.color = clr;
        }
    }

    Connections{
        target: blueLoader.item;
        onColorPicked:{
            coloredText.color = clr;
        }
    }
}

如果没有显示指定Loader的大小,那么Loader的大小会和加载的Component大小一致,如果给Loader指定了大小,那么加载的Component大小会随着指定大小改变。另外,Loader的item属性指向它加载的顶层组件的Item,在本例中,item属性就指向颜色选择组件的Rectangle对象。
在这里插入图片描述

从文件加载组件

import QtQuick 2.0

Rectangle {
    width: 320;
    height: 240;
    color: "#EEEEEE";

    Text{
        id: coloredText;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top: parent.top;
        anchors.topMargin: 4;
        text: "Hello World!";
        font.pixelSize: 32;
    }

    Loader{
        id: redLoader;
        width: 80;
        height: 60;
        focus: true;
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        source: "ColorPicker.qml";
        KeyNavigation.right: blueLoader;
        KeyNavigation.tab: blueLoader;

        onLoaded: {
            item.color = "red";
            item.focus = true;
        }

        onFocusChanged: {
            item.focus = focus;
        }
    }

    Loader{
        id: blueLoader;
        anchors.left: redLoader.right;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        source: "ColorPicker.qml";
        KeyNavigation.left: redLoader;
        KeyNavigation.tab: redLoader;

        onLoaded: {
            item.color = "blue";
        }

        onFocusChanged: {
            item.focus = focus;
        }
    }

    Connections{
        target: redLoader.item;
        onColorPicked:{
            coloredText.color = clr;
            if(!redLoader.focus){
                redLoader.focus = true;
                blueLoader.focus = false;
            }
        }
    }

    Connections{
        target: blueLoader.item;
        onColorPicked:{
            coloredText.color = clr;
            if(!blueLoader.focus){
                blueLoader.focus = true;
                redLoader.focus = false;
            }
        }
    }
}

代码改动如下:
1.将sourceComponent修改为source,其值为ColorPicker.qml.
2.在两个Connections对象的onColorPicked信号处理器中,设置了Loader焦点属性,从而改变加载的外部Component文件的焦点,实现边框颜色改变。

Loader动态创建与销毁组件

import QtQuick 2.0
import QtQuick.Controls 1.2

Rectangle {
    id: rootItem;
    width: 320;
    height: 240;
    color: "#EEEEEE";
    property var colorPickerShow: false;

    Text{
        id: coloredText;
        anchors.horizontalCenter: parent.horizontalCenter;
        anchors.top: parent.top;
        anchors.topMargin: 4;
        text: "Hello World!";
        font.pixelSize: 32;
    }

    Button{
        id: ctrlButton;
        text: "Show";
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;

        onClicked: {
            if(rootItem.colorPickerShow){
                redLoader.sourceComponent = undefined;
                blueLoader.source = "";
                rootItem.colorPickerShow = false;
                ctrlButton.text = "Show";
            }
            else{
                redLoader.source = "ColorPicker.qml";
                redLoader.item.colorPicked.connect(onPickedRed);
                blueLoader.source = "ColorPicker.qml";
                blueLoader.item.colorPicked.connect(onPickedBlue);
                redLoader.focus = true;
                rootItem.colorPickerShow = true;
                ctrlButton.text = "Hide";
            }
        }
    }

    Loader{
        id: redLoader;
        anchors.left: ctrlButton.right;
        anchors.leftMargin: 4;
        anchors.bottom: ctrlButton.bottom;

        KeyNavigation.right: blueLoader;
        KeyNavigation.tab: blueLoader;

        onLoaded: {
            if(item != null){
                item.color = "red";
                item.focus = true;
            }
        }

        onFocusChanged: {
            if(item != null){
                item.focus = focus;
            }
        }
    }

    Loader{
        id: blueLoader;
        anchors.left: redLoader.right;
        anchors.leftMargin: 4;
        anchors.bottom: redLoader.bottom;

        KeyNavigation.left: redLoader;
        KeyNavigation.tab: redLoader;

        onLoaded: {
            if(item != null){
                item.focus = "blue";
            }
        }

        onFocusChanged: {
            if(item !=null){
                item.focus = focus;
            }
        }
    }

    function onPickedBlue(clr){
        coloredText.color = clr;
        if(!blueLoader.focus){
            blueLoader.focus = true;
            redLoader.focus = false;
        }
    }

    function onPickedRed(clr){
        coloredText.color = clr;
        if(!redLoader.focus){
            redLoader.focus = true;
            blueLoader.focus = false;
        }
    }
}

上述代码中,通过将redLoader的sourceComponent属性设置为undefined,将blueLoader的source属性设置为空串来卸载它们,这是卸载Loader所加载的组件的两种方式。
使用Loader控制组件的动态创建与销毁,只是Qt Quick提供的动态维护对象的两种方式中的一种,还有一种,就是在ECMAScript中动态创建QML对象。

ECMAScript中动态创建对象

在ECMAScript中,有两种方式可以动态创建对象:
1.使用Qt.createComponent()动态地创建一个组件对象,然后使用Component的createObject()方法创建对象。
2.使用Qt.createQmlObject()从一个QML字符串直接创建一个对象。
如果你在一个QML文件中定义了一个组件(例如ColorPicker),而你想动态的创建它的实例,使用Qt.createComponent()是比较好的方式,而如果你的QML对象本身是在应用运行时产生的,那么Qt.createQmlObject()可能是比较好的选择。

从组件文件动态创建Component

Qt对象的createComponent()方法可以根据QML文件动态创建一个组件:

object createComponent(url, mode, parent)

url:QML文档的本地路径或者网络路径
mode:指定创建组件的模式,可以是Component.PreferSynchronous(同步模式)或Component.Asynchronous(异步模式),默认使用同步模式
parent:指定组件的父对象

一旦拥有了组件对象,就可以调用createObjcet()方法创建一个组件的实例:createObject()方法有两个参数,第一个参数指定创建的Item的parent,第二个参数指定创建Item的属性参数。

import QtQuick 2.0
import QtQuick.Controls 1.2

Rectangle {
    id: rootItem;
    width: 360;
    height: 300;
    property var count: 0;
    property Component component: null;

    Text{
        id: coloredText;
        text: "Hello World!";
        anchors.centerIn: parent;
        font.pixelSize: 24;
    }

    function changeTextColor(clr){
        coloredText.color = clr;
    }

    function createColorPicker(clr){
        if(rootItem.component == null){
            rootItem.component = Qt.createComponent("ColorPicker.qml");
        }
        var colorPicker;
        if(rootItem.component.status == Component.Ready){
            colorPicker = rootItem.component.createObject(rootItem, {"color":clr,"x":rootItem.count*55,"y":10});
            colorPicker.colorPicked.connect(rootItem.changeTextColor);
        }
        rootItem.count++;
    }

    Button{
        id: add;
        text: "add";
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        onClicked: {
            createColorPicker(Qt.rgba(Math.random(),Math.random(),Math.random(),1));
        }
    }
}

从QML字符串动态创建Component

var newObject = Qt.createQmlObject('import QtQuick 2.2; Rectangle{color:red; width:20; height:20}', parentItem, "dunamicSnippet1");

第一个参数为要创建QML对象的字符串,就像一个QML文档一样,你需要导入你用到的所有类型和模块;
第二个参数用于指定要创建对象的父对象;
第三个参数用于给新创建的对象关联一个文件路径,主要用于报告错误;

销毁动态创建的对象

  有些软件,在不需要一个动态创建的QML对象时,仅仅只是把它的visible属性设置为false或者把opacity属性设置为0,而不是删除这个对象,如果动态创建的对象很多,无用的对象都这么处理而不直接删除,那会给软件带来较大的性能问题,比如内存占用增多,运行速度变慢等。所以,动态创建的对象,不再使用时,最好把它删除。
  这里所说的动态创建的对象,特指使用Qt.createComponent()或Qt.createQmlObject()方法创建的对象,而使用Loader创建的对象,应该通过将source设置为空串或者将sourceComponent设置为undefined触发Loader销毁他们。
  要删除一个对象,可以调用其destroy方法,这个方法有一个可选参数,指定延迟多少毫秒再删除这个对象,默认值为0,但是即便你设置为0,对象也不会立即删除,QML引擎会在当前代码块执行结束后的某个合适的时刻删除他们,所以,即便在一个对象内部调用destroy方法也是安全的。

import QtQuick 2.0
import QtQuick.Controls 1.2

Rectangle {
    id:rootItem;
    width: 360;
    height: 300;
    property var count: 0
    property Component component: null;

    Text{
        id: coloredText;
        text:"Hello World!";
        anchors.centerIn: parent;
        font.pixelSize: 24;
    }

    function changTextColor(clr){
        coloredText.color = clr;
    }

    function createColorPicker(clr){
        if(rootItem.component == null){
            rootItem.component = Qt.createComponent("ColorPicker.qml");
        }
        var colorPicker;
        if(rootItem.component.status == Component.Ready){
            colorPicker = rootItem.component.createObject(rootItem, {"color":clr,"x":rootItem.count*55,"y":10});
            colorPicker.colorPicked.connect(rootItem.changTextColor);

            if(rootItem.count %2 ==1){
                colorPicker.destroy(1000); //隔一个删除一个组件对象
            }
        }
        rootItem.count++;
    }

    Button{
        id: add;
        text: "add";
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        onClicked: {
            createColorPicker(Qt.rgba(Math.random(), Math.random(), Math.random(), 1));
        }
    }
}
import QtQuick 2.0
import QtQuick.Controls 1.2

Rectangle {
    id:rootItem;
    width: 360;
    height: 300;
    property var count: 0
    property Component component: null;
    property var dynamicObjects: new Array();

    Text{
        id: coloredText;
        text:"Hello World!";
        anchors.centerIn: parent;
        font.pixelSize: 24;
    }

    function changTextColor(clr){
        coloredText.color = clr;
    }

    function createColorPicker(clr){
        if(rootItem.component == null){
            rootItem.component = Qt.createComponent("ColorPicker.qml");
        }
        var colorPicker;
        if(rootItem.component.status == Component.Ready){
            colorPicker = rootItem.component.createObject(rootItem,
                                                          {
                                                              "color":clr,
                                                              "x":rootItem.dynamicObjects.length*55,
                                                              "y":10
                                                          });
            colorPicker.colorPicked.connect(rootItem.changTextColor);
            rootItem.dynamicObjects[rootItem.dynamicObjects.length] = colorPicker;
        }
        rootItem.count++;
    }

    Button{
        id: add;
        text: "add";
        anchors.left: parent.left;
        anchors.leftMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        onClicked: {
            createColorPicker(Qt.rgba(Math.random(), Math.random(), Math.random(), 1));
        }
    }

    Button{
        id: del;
        text: "del";
        anchors.left: add.right;
        anchors.leftMargin: 4;
        anchors.bottom: add.bottom;
        onClicked: {
            if(rootItem.dynamicObjects.length > 0){
                //删除数组最后一个元素,并且返回被删除的元素组成的数组
                var deleted = rootItem.dynamicObjects.splice(-1,1);
                deleted[0].destroy();
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vegetablesssss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值