简体   繁体   中英

Why is my QML GroupBox not sizing properly within a layout?

I'm trying to make two group boxes appear next to each other so that each one occupies 50% of the window. However, it looks like the width of each GroupBox is somehow changed depending on the GroupBox title length.

If the GroupBox title is the same for both GroupBox's, it will be 50% of the window. If they are not the same, the GroupBox with the longer title will occupy more of the screen.

It doesn't make sense to me for this to happen, how can I fix it so the length of the title doesn't effect the size of the GroupBox in a layout?

Here's sample code to reproduce the issue...

AppGroupBox.qml

import QtQuick 2.0
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.12

GroupBox {
    Layout.alignment: Qt.AlignLeft | Qt.AlignTop
    spacing:0
    label.x: 0
}

AppRowLayout.qml

import QtQuick 2.0
import QtQuick.Layouts 1.12

RowLayout {
    Layout.alignment: Qt.AlignLeft | Qt.AlignTop
    spacing: 0
}

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    width: 640
    height: 480
    visible: true


    AppRowLayout {
        anchors.fill: parent

        AppGroupBox {
            title: "Short Name"
            Layout.fillWidth: true
        }

        AppGroupBox {
            title: "Much Longer Name"
            Layout.fillWidth: true
        }
    }
}

Qt will distribute the free space relative to the Layout.preferredWidth (or implicitWidth if that isn't defined). So, a group box with a longer title will get more space by default, as its implicitWidth is larger.

The solution is to use a fixed preferredWidth for all elements in the RowLayout :

GroupBox {
    ...
    Layout.preferredWidth: 50 // or any other fixed value.
    Layout.minimumWidth: implicitWidth // OPTIONAL: may be usefull on small screens to ensure the box is not made smaller than the title width
    ...
}

Note on attached properties:

Layout.alignment is an attached property available on the children of a Layout ( RowLayout , GridLayout or ColumnLayout ). Setting it directly inside a RowLayout object is useless (except when the RowLayout itself is a child of another Layout item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM