QML 元素自適應(yīng)內(nèi)部元素的寬高變化

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
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容