Home > Back-end >  QML Grid remove spacing if column is not visible
QML Grid remove spacing if column is not visible

Time:06-20

I have a Grid that has a layout with 4 rows and 2 columns like this:

import QtQuick 2.9
import QtQuick.Controls 2.2

Item {
    id: page

    Grid {
        property int buttonSize: height * 0.2
        property int spacingSize: height * 0.04

        id: grid
        height: parent.height
        spacing: spacingSize
        anchors.horizontalCenter: parent.horizontalCenter
        topPadding: spacingSize
        flow: Grid.TopToBottom
        columns: 2
        rows: 4

        Rectangle {
            color: "blue"
            height: grid.buttonSize
            width: grid.buttonSize
            visible: true //this comes from c  , not always true
        }
        
        Rectangle {
            color: "blue"
            height: grid.buttonSize
            width: grid.buttonSize
            visible: true //this comes from c  , not always true
        }
        
        Rectangle {
            color: "blue"
            height: grid.buttonSize
            width: grid.buttonSize
            visible: true //this comes from c  , not always true
        }
        
        Rectangle {
            color: "blue"
            height: grid.buttonSize
            width: grid.buttonSize
            visible: true //this comes from c  , not always true
        }
        
        Rectangle {
            color: "blue"
            height: grid.buttonSize
            width: grid.buttonSize
            visible: true //this comes from c  , not always true
        }
    }
}

If I have 5 visible elements (2 columns are drawn), everything works fine, but if I have 4 or less items visible (1 column is drawn), the grid keeps the column spacing visible and the elements are not centered.
How can I fix this? Thank you

CodePudding user response:

The solution was simple, just remove the number of columns. This will make the Grid create columns only when necessary.

  • Related