如何动态获取 RowLayout 中的 QML 组件大小?

问题描述 投票:0回答:1

我尝试获取 RowLayout 内组件的宽度。当组件完成时,我得到 0。当我尝试调整窗口大小时,我正确地得到了这个宽度。为什么?运行这个应用程序后如何获得这个尺寸?

应用程序输出:

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

应用程序.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"
        }
    }
}
qt qml
1个回答
0
投票

这是因为 Component.onCompleted 任务中尚未完全计算 RowLayout 尺寸。在完成之前获取宽度将返回 0

我建议在检索数据之前添加一些等待时间。您可以使用

Qt.callLater

© www.soinside.com 2019 - 2024. All rights reserved.