1
votes

I'm new to QML, so I may be asking something obvious. I'm struggling to stack elements in ColumnLayout on top of each other. There's just too much spacing between them I can't do anything about. See screenshot for more details:

enter image description here

Here's the actual QML:

ColumnLayout {
    anchors.fill: parent
    spacing: 0

    Rectangle {
        color: "blue"
        Layout.fillWidth: true
        height: 50
    }

    Rectangle {
        color: "red"
        Layout.fillWidth: true
        height: 50
    }

    Rectangle {
        color: "yellow"
        Layout.fillWidth: true
        height: 50
    }
}

What I'm trying to do is to have the rectangles aligned top to bottom and have spacing between them maybe 2-3 pixels.

Thanks

1
Isn't it a duplicate of this question?BaCaRoZzo
@BaCaRoZzo I would certainly consider that a better solution in general than the accepted answer.Mitch
@Mitch Well, there's also another duplicate questio/answer with the exact same words by Grecko (couldn't find it) so yeah, it's the "accepted way". Also, having margins and alignment properties in any Layout does seems to collide with the answer statement that "layouts good thing if you don't need to manage positions".BaCaRoZzo
I think you are right, this is a dupe, but the other answer needs a tidy up, I will post a comment there.Mark Ch

1 Answers

1
votes

Your code will works fine if you remove the filling to parent and place there filling just to width

anchors.left: parent.left
anchors.right: parent.right 

After that the code will looks like this

ColumnLayout {
    anchors.left: parent.left
    anchors.right: parent.right
    spacing: 2 //spacing between items in layout
    Rectangle {
        color: "blue"
        Layout.fillWidth: true
        height: 50
    }
    Rectangle {
    ...
    }
    Rectangle {
    ...
    }
}

By doing this, you will give to ColumnLayout rights to manage himself's height. Its height will related to its children's height and will not be stretched to the parent.

Another way is to manage items through anchor

Item {
  id: item1
}
Item {
  id: item2
  anchor.top: item1.bottom
  anchor.topMargin: 2 
}
Item {
  id: item3
  anchor.top: item2.bottom
  anchor.topMargin: 3 
}

Layouts good thing if you don't need to manage positions of items in specific way inside layout.

Also it would be helpful to you to check this Use Case - Positioners and Layouts In QML