Qt QML 杂记

QML 元素自适应内部元素的宽高变化

2021-03-29  本文已影响0人  赵者也

QML 元素自适应内部元素的宽高变化

1. 背景

在 QML 开发中我们常常需要处理包含大量视图元素的情况。其中,有时候我们需要面对如下的情况:外部视图元素可能需要根据内部的子元素的宽高的变化。

Clicked Center Rect Update Width

如上图我们希望图中的中间绿色边框的子控件的宽度变化时,外围的父控件的宽度也更新宽度,此时可以使用 Item 元素的 childrenRect 属性来更新外围控件的宽度。具体可以参见下面的示例代码:

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 1000
    height: 400
    color: "white"
    title: "Test childrenRect"

    Rectangle {
        color: "#B97A57"
        border.color: "black"
        border.width: 4
        anchors.centerIn: parent
        width: childrenRect.width + 47 + 47
        implicitHeight: 300

        Rectangle {
            id: id_left
            color: "#00A2E8"
            border.color: "#FFF200"
            border.width: 4
            implicitWidth: 200
            implicitHeight: 200
            anchors.left: parent.left
            anchors.leftMargin: 47
            anchors.verticalCenter: parent.verticalCenter
        }

        Rectangle {
            id: id_center
            color: "#C3C3C3"
            border.color: "#22B14C"
            border.width: 4
            implicitHeight: 200
            implicitWidth: 300
            anchors.left: id_left.right
            anchors.leftMargin: 20
            anchors.verticalCenter: parent.verticalCenter

            Text {
                anchors.centerIn: parent
                text: "Click Me"
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    id_center.width += 10
                }
            }
        }

        Rectangle {
            id: id_right
            color: "#3F48CC"
            border.color: "#FFAEC9"
            border.width: 4
            implicitHeight: 200
            implicitWidth: 150
            anchors.left: id_center.right
            anchors.leftMargin: 20
            anchors.verticalCenter: parent.verticalCenter
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读