Search code examples
qtqml

How can I get QML Component size in RowLayout dynamically?


I try to get width of component inside the RowLayout. When component is completed I get 0. When I try to resize window size, I get this width correctly. Why? How can I get this size after running this app?

App output:

qml: onCompleted: rectangle width is 0
qml: onWidthChanged: rectangle width is 300
qml: onWidthChanged: rectangle width is 301
qml: onWidthChanged: rectangle width is 302
qml: onWidthChanged: rectangle width is 305
qml: onWidthChanged: rectangle width is 306
qml: onWidthChanged: rectangle width is 307

App.qml

import QtQuick 6.2

Window {
    width: 600
    height: 400
    visible: true

    Screen01 {
        id: mainScreen
        anchors.fill: parent
    }

    onWidthChanged: {
        console.log("onWidthChanged: rectangle width is " + mainScreen.rectangle2.width)
    }

    Component.onCompleted: {
        console.log("onCompleted: rectangle width is " + mainScreen.rectangle2.width)
    }

}

Screen01.ui.qml

import QtQuick 6.2
import QtQuick.Layouts

Rectangle {
    id: rectangle

    property alias rectangle2: rectangle2

    RowLayout {
        id: rowLayout
        anchors.fill: parent
        spacing: 0

        Rectangle {
            id: rectangle1
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "red"
        }

        Rectangle {
            id: rectangle2
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "yellow"
        }
    }
}

Solution

  • I connected to signal widthChanged of Rectangle object:

    App.qml

    Window {
    //... 
    
        Screen01 {
            id: mainScreen
            anchors.fill: parent
        }
    
        Connections{
            target: mainScreen.rectangle2
            onWidthChanged: {
                console.log("rectangle width is " + mainScreen.rectangle2.width)
            }
        }
    }