QML Component 内嵌使用方式

版权声明:未经许可,请勿转载! https://blog.csdn.net/weixin_37204973/article/details/82691904

       Component ,顾名思义就是组件。 Component 既可以定义在独立的 qml 文件中,也可以嵌入到其它的 qml 文档中来定义。我们可以根据需要,自己选择如何定义,下面是我自己写的一个嵌入在qml 文档中的一个 Component

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4

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

    Loader {
        id: closeButton
        //水平居中
        anchors.horizontalCenter: parent.horizontalCenter
        //垂直居中
        anchors.verticalCenter: parent.verticalCenter
        //加载组件
        sourceComponent : colorComponent        
        onLoaded: {
            //修改组件内部属性
            item.text = "Close"
        }
    }
    //绑定组件信号
    Connections {
        target: closeButton.item
        onClicked: Qt.quit()
    }

    //组件
    Component{
        id: colorComponent
        //组件每部对象
        Button
        {
            width: 60
            height: 30
            style:ButtonStyle{
                background: Rectangle{
                    radius: 4
                    border.color: "#3cb9b7"
                    antialiasing:true

                    gradient: Gradient{
                        GradientStop{ position: 0; color: control.pressed? "#ff00d5d5" : control.hovered ? "#9900d5d5":"#00a2fcff"}
                        GradientStop{ position: 1; color: control.pressed? "#ff00d5d5" : control.hovered ? "#9900d5d5":"#00a2fcff"}
                    }
                }
            }
        }
    }
}
  • 有时候我们的组件只在某一个文件中需要多次用到,那么就可以在文件中嵌入一个 Component ,利用 Loader 动态进行加载,达到复用的目的。

  • Component 的定义与QML 文档定义类似,只能包含一个顶层的item,如上面代码中的 Button,并且在这个item 之外不能定义除id 以外的任何数据及信号,如上面代码中,我们只定义了 id: colorComponent;而在item 内,我们则可以包含更多的子元素来协同工作了

  • Loader 可以使用 source 来动态装载一个qml 文档,也可以使用 sourceComponent 来装载一个Component 对象。当 Loader 的 source 或 sourceComponent 属性发生变化时,它之前加载的 Component 会自动销毁,新对象会被加载。将 source 设置为一个空字符串或将 sourceComponent 设置为 undefined ,将会销毁当前加载的对象,相关的资源也会被释放,而 Loader 对象则变成一个空对象。

  • Loader 的item 属性指向它加载的组件顶层item,比如上面代码加载了一个button,其中 item.text 就是我们按键文本,通过改变它,就可以设置按键的相关文本,它暴露出来的接口,如属性,信号,都可以通过item 的属性来访问。

  • 信号我们则使用 Connections 的对象,其 target 指向 closeButton.item,也就是Component 中的 button ,所以我们可以直接响应它的信号。

猜你喜欢

转载自blog.csdn.net/weixin_37204973/article/details/82691904