12 QML之作用域

作用域

1.作用

  • 表达式可以访问哪些变量;
  • 重名时的优先级

2.绑定的作用域对象

Items{
		anchors.left:parent.left
} 

3.组件作用域

  • QML文件每个组件(ex Rectangel Button label)都定义了一个逻辑作用域
  • 每个文件都至少有一个根组件(Window)

4.作用域使用技巧

  • id.property(root.width)

代码

//main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.0
Window {
    id:root//root和parent作用等同
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    property int mywidth:200//作用域window的所有对象都能引用
    Rectangle{
        id:firstRec
        width:root.mywidth
        height:fheight
        anchors.centerIn: parent//作用域是整个window
        color: "red"

        property int fheight: 150

        Text {
            id: text
            text: qsTr("hello")
            anchors.fill:parent
            //anchors.centerIn: parent
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }

    }
    Rectangle{
        id:secondRec
        width:mywidth
        height:100
        color: "blue"
        anchors.left: parent.left//这个地方注意不能用root.left
        anchors.bottom: parent.bottom


        Label{
            id:label
            color: "gray"
            font.bold:true
            font.pixelSize: 20
            //anchors.centerIn: parent
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            text:"label"
        }
    }

    Button{
        id:buttton
        width: 200
        height: 100
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        text: "button"
        background: Rectangle{
            color: "gray"
        }

        onClicked: {
            console.log("firstRec.fheight: " + firstRec.fheight)//通过id.property来访问不在当前组件下的属性 
            console.log("label.text: " + label.text)
        }
    }
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值