首页 > 解决方案 > QML RowLayout 不会根据内容动态调整大小

问题描述

我对 Qt Widgets 有一些经验,但最近才开始使用 QML。

我面临的问题是我希望 QML 中定义的一些布局能够自动调整以适应它们的内容。这有效,但不是动态的,即如果内容更改布局不适应。使用旧式(非 QML)布局/小部件方法,这会自动发生。

这是一个示例(我的代码看起来不同并且由不同的文件组成,但我将这个 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 达到同样的效果?

标签: qtlayoutqml

解决方案


您可以通过将green的大小设置为 child的隐式大小来使其工作。我不完全确定为什么,似乎属性没有正确更新。RectangleColumnLayoutchildrenRect

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;
        }
    }
}

推荐阅读