QML布局管理之基于锚的布局

基于锚(anchors)的布局

QtQuick还提供了一种使用锚(anchors)的概念来进行项目布局的方法。每一个项目都可以认为有一组无形的“锚线”:left、horizontalCenter、right、top、verticalCenter、baseline和bottom,图中没有显示baseline,它是一条假想的线,文本坐落在这条线上。对于没有文本的项目,它与top相同。对于本节的内容,大家可以在Qt帮助中通过Positioning with Anchors关键字查看。
在这里插入图片描述

    Rectangle {
        id: rect1
        width: 50; height: 50; color: "blue"
    }

    Rectangle {
        id: rect2
        width: 50; height: 50; color: " red"
        // rect2左边的对齐rect1的右边
        anchors.left: rect1.right
    }

使用anchors.fill等价于设置left、right、top和bottom 锚定到目标项目的left、right、top和bottom;anchors.centerIn等价于设置verticalCenter和 horizontalCenter锚定到目标项目的 verticalCenter和horizontalCenter等。

锚边距和偏移

锚定系统也允许为一个项目的锚指定边距(margin)和偏移(offset)。边距指定了项目锚到外边界的空间量,而偏移则允许使用中心锚线进行定位。一个项目可以通过leftMargin、rightMargin、topMargin和bottomMargin独立指定锚边距;也可以使用 anchor.margins来为所有的4个边指定相同的边距。锚偏移可以使用horizontalCenterOffset、verticalCenterOffset和 baselineOffset来指定。

    Rectangle {
        id: rect1
        width: 50; height: 50; color: "blue"
    }

    Rectangle {
        id: rect2
        width: 50; height: 50; color: " red"
        // rect2左边的对齐rect1的右边
        anchors.left: rect1.right
        // 5像素的边距
        anchors.leftmargin: 5
    }

运行时改变锚

Qt Quick 提供了AnchorChanges类型,以便在运行时修改项目的锚,它需要在状态State中进行。AnchorChanges不能修改项目的边距,需要时可以使用PropertyChanges完成。

    Rectangle {
        id: win
        width: 120; height: 120
        color: "black"
        Rectangle { id: myRect; width: 50; height: 50; color: "red"}
        states: State {
            name: "reanchored"
            AnchorChanges {
                target: myRect
                anchors.top: win.top
                anchors.bottom: win.bottom
            }
            PropertyChanges {
                target: myRect
                anchors.topMargin: 10
                anchors.bottomMargin: 10

            }
        }
        MouseArea {
            anchors.fill: parent;
            onClicked: win.state = "reanchored"
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值