Search code examples
qmlgrid-layout

QML - How to correctly set an implicitWith to a GridLayout


I'm using Qml 5.12 and basically trying to set an implicitWidth to a GridLayout.

For that, I have a purple rectangle and set the rectangle's width to the GridLayout.

The red rectangle fit with the GridLayout so I can see the width of my GridLayout.

Here's my code:

Rectangle { anchors.fill: gl; color: "red"; opacity: 0.22 }
Rectangle { id: rect; width: 350; height: 30; color: "purple"; }

GridLayout
{
    id: gl
    y: 35
    implicitWidth: rect.width
    columns: 2
    Label { text: "This is a test" }
    SpinBox { Layout.alignment: Qt.AlignRight }
}

If I run the code, I expect to have my both rectangle with the same width. But the actual result is that the red rectangle is smaller. So the implicitWidth was not considerate.

Can anybody tell my why ?

Thank's !


Solution

  • The GridLayout compute its own implicitWidth based on its children's implicitWidth. So the value you set gets overwritten by the computed one.

    implicitWidth is the width an Item wants to have (and the one it would have if no width is explicitely set). Setting it based on something else than its children or some internal value makes little sense.

    Here you want the GridLayout to be the exact size of your Rectangle so just set its width property.