QML RowLayout不会根据内容动态调整大小

我对Qt小部件有一定的经验,但是直到最近才开始使用QML。

我面临的问题是我希望QML中定义的某些布局能够自动调整以适合其内容。这是有效的,但不是动态的,即,如果内容更改,布局将无法适应。使用旧式(非QML)的Layout / Widget方法,这自动发生。

这是一个示例(我的代码看起来不同,并且由不同的文件组成,但是我将此MWE粘贴在一起以演示问题):

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.2

Window {
    id: root
    visible: true
    width: 640
    height: 480
    property var nbx: 3

    Column {
        RowLayout {
            Repeater {
                model: 3
                Rectangle {
                    width:  childrenRect.width     
                    height: childrenRect.height
                    color: "green"
                    ColumnLayout {
                        Rectangle {
                            height: 10
                        }
                        RowLayout {
                            Repeater {
                                model: root.nbx
                                Rectangle {
                                    width:  20
                                    height: 20
                                    color: "orange"
                                }
                            }
                        }
                    }
                }
            }
        }

        Button {
            text: "5 boxes"
            onClicked: root.nbx= 5;
        }
        Button {
            text: "2 boxes"
            onClicked: root.nbx = 2;
        }
    }
}

如何使用QML达到相同的目的?

ygp47 回答:QML RowLayout不会根据内容动态调整大小

您可以通过将绿色Rectangle隐式大小设置为子ColumnLayout隐式大小来使其工作。我不确定为什么,似乎childrenRect属性没有正确更新。

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.2

Window {
    id: root
    visible: true
    width: 640
    height: 480
    property var nbx: 3

    ColumnLayout {
        RowLayout {

            Repeater {
                model: 3

                Rectangle {
                    implicitHeight: col1.implicitHeight   // <--- here is the change
                    implicitWidth: col1.implicitWidth
                    color: "green"

                    ColumnLayout {
                        id: col1

                        Rectangle {
                            height: 10
                        }
                        RowLayout {
                            Repeater {
                                model: root.nbx
                                Rectangle {
                                    width:  20
                                    height: 20
                                    color: "orange"
                                }
                            }
                        }
                    }
                }
            }
        }

        Button {
            text: "5 boxes"
            onClicked: root.nbx= 5;
        }
        Button {
            text: "2 boxes"
            onClicked: root.nbx = 2;
        }
    }
}
本文链接:https://www.f2er.com/3052216.html

大家都在问