Spacer Item in QML Layouts

13.2k views Asked by At

I want to create a layout in QML and I'd like to add a spacer item (the bottom selected item from the image below) just as you do using widgets like so:

enter image description here

But I couldn't find anything to suit this on the QtQuick side of things...is it possible to have this kind of layout in QML w/o using the anchoring system? I'd prefer the layouts approach...

2

There are 2 answers

1
GrecKo On BEST ANSWER

You can simply use an Item with Layout.fillHeight: true :

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    ColumnLayout {
        anchors.fill: parent
        Button {
            Layout.fillWidth: true
            text: "PushButton"
        }
        Button {
            Layout.fillWidth: true
            text: "PushButton"
        }
        Label {
            Layout.fillWidth: true
            text: "TextLabel"
        }
        Item {
            // spacer item
            Layout.fillWidth: true
            Layout.fillHeight: true
            Rectangle { anchors.fill: parent; color: "#ffaaaa" } // to visualize the spacer
        }
    }
}

EDIT: Alternatively here, you could have used a Column with no spacer item since a Column just positions its children from top to bottom and don't spread them to take all the available space.

0
tanius On

For those coming from Qt widgets and for comparison: the intended solution in QML for this situation is the anchoring system that the question mentions. In this case, it would look as follows, and I think it's not so bad :)

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true

    ColumnLayout {
        // anchors.fill sets all four directional anchors.
        // Loosening one yields the space at the bottom.
        anchors.fill: parent
        anchors.bottom: undefined

        // Alternative approach: only set the three anchors we want.
//      anchors.top: parent.top
//      anchors.left: parent.left
//      anchors.right: parent.right

        Button {
            Layout.fillWidth: true
            text: "PushButton"
        }
        Button {
            Layout.fillWidth: true
            text: "PushButton"
        }
        Label {
            Layout.fillWidth: true
            text: "TextLabel"
        }
    }
}