QML 元素自適應(yīng)內(nèi)部元素的寬高變化
1. 背景
在 QML 開發(fā)中我們常常需要處理包含大量視圖元素的情況。其中及志,有時(shí)候我們需要面對(duì)如下的情況:外部視圖元素可能需要根據(jù)內(nèi)部的子元素的寬高的變化。
Clicked Center Rect Update Width
如上圖我們希望圖中的中間綠色邊框的子控件的寬度變化時(shí),外圍的父控件的寬度也更新寬度,此時(shí)可以使用 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
}
}
}