How to give specific spacing to items in a QML layout?

前端 未结 2 1749
暗喜
暗喜 2020-12-11 05:49

I have a ColumnLayout, which has its anchor set to anchor.fill: parent, therefore it has already a set dimension, which depends on its parent dimen

2条回答
  •  温柔的废话
    2020-12-11 06:15

    The accepted answer is one valid approach, however, there are others.

    1) ColumnLayout decides its own height

    If you are simply trying to place items in a column from the top downwards, then there is no need to force the height of the ColumnLayout.

    Instead of anchors.fill: parent use width: parent.width

    and let the ColumnLayout size itself to fit its contents, as below:

    import QtQuick 2.0
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.0
    
    ApplicationWindow {
        visible: true
    
        width: 100
        height: 200
    
        ColumnLayout {
            width: parent.width
            spacing: 2
    
            Rectangle {
                height: 50
                width: 50
                color: "red"
            }
            Rectangle {
                height: 50
                width: 50
                color: "green"
            }
            Rectangle {
                height: 50
                width: 50
                color: "blue"
            }
        }
    }
    

    2) ColumnLayout resizes the items to achieve desired spacing.

    If there are too many or too few items to perfectly fill the layout, you can allow the layout to resize the items (instead of resizing the spacing).

    The following attached properties control how the layout treats your items, when deciding what can be stretched or shrunk in order to fit the layout:

    • Layout.preferredHeight
    • Layout.minimumHeight
    • Layout.maximumHeight
    • Layout.fillHeight

    Example, where Rectangles are enlarged slightly to achieve the desired spacing:

    import QtQuick 2.0
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.0
    
    ApplicationWindow {
        visible: true
    
        width: 100
        height: 200
    
        ColumnLayout {
            anchors.fill: parent
            spacing: 2
    
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredHeight: 50
                width: 50
                color: "red"
            }
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredHeight: 50
                width: 50
                color: "green"
            }
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredHeight: 50
                width: 50
                color: "blue"
            }
        }
    }
    

提交回复
热议问题