QML Component创建方法

1. 使用Component在QML中嵌入组件

Component是Qt框架或者开发者封装好的、只暴露必要接口的QML类型,可以重复使用。要再QML中嵌入Component的定义,需要使用Component对象。

  • Component只能包含一个顶层的Item,而且在这个Item之外不能定义任何的数据,除了Id。
  • Component通常用来给一个View提供图形化组件。
  • Component不是Item的派生类,而是从QQmlComponent继承而来的,虽然它通过自己的顶层Item为其他的View提供可视化组件,但它本身不是可见元素。

下面是一个简单的在QML文档中定义Component的示例:

Component {
    id: itemCompont
    Rectangle {
        id: compontRect
        color: 'blue'
        implicitWidth: 200
        implicitHeight: 50

        signal deleteThis()

        Text {
            id: interText
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.verticalCenter: parent.verticalCenter
            text: qsTr("text")
        }
        Button {
            anchors.margins: 5
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            anchors.right: parent.right
            text: '删除'

            onClicked: {
                compontRect.deleteThis()
            }
        }
    }
}

2. 在文件中定义组件

很多时候我们把QML文件定义在一个文件中,方便被其他的QML文件调用。可以直接使用文件名作为组件的名称,在其他的QML文件中使用。上面组件中的代码可以单独定义在一个文件中,本示例的文件名为TestCompont.qml

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.4

Rectangle {
    id: compontRect
    color: Qt.rgba(0.8, 0.4, 0.4, 1.0)
    implicitWidth: 200
    implicitHeight: 50
    property var currentObject: ''

    signal deleteThis(var obj)

    // 设置文字的内容
    function setCurrentText(textName) {
        interText.text = textName
    }

    Text {
        id: interText
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.verticalCenter: parent.verticalCenter
        text: qsTr("text")
    }
 
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值