qml using Row to align components in the center

user42140 picture user42140 · Nov 1, 2017 · Viewed 8.5k times · Source

I am using Row to layout some buttons on a Rectangle which is my custom toolbar implementation. The problem is no matter what I do, the components are always aligned from the left. I would like them to be aligned with the center of the row and flowing outwards towards the edges. The code looks as follows:

Rectangle {
        id: toolbar
        color: "green"
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        height: 100

        Row
        {
            anchors.fill: parent                
            anchors.horizontalCenter: parent.horizontalCenter
            spacing: 60

            ToolButton {
                height: parent.height
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }

            ToolButton {
                height: parent.height
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }
        }
 }

My buttons are always laid out starting from the left side of the row. Rather I would like to have them laid out relative to the center of the toolbar. I thought specifying this line anchors.horizontalCenter: parent.horizontalCenter should achieve that but no matter what I try, the components are laid out from the left boundary.

Answer

piper2200s picture piper2200s · Sep 30, 2020

If you set your Row's alignments to center in the parent object and then make the Row's width adjust to the childrenRect's width then you can have items expand from the center of the object. Note: you may need to set the widths of the ToolButton's in order for the childrenRect to have it's width value populated.

   Rectangle {
        id: toolbar
        color: "green"
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        height: 100

        Row
        {
            anchors{
                horizontalCenter: parent.horizontalCenter
                verticalCenter: parent.verticalCenter
            }
            height: parent.height
            width: childrenRect.width
            spacing: 60

            ToolButton {
                height: parent.height
                width: 50
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }

            ToolButton {
                height: parent.height
                width: 50
                Image {
                    anchors.verticalCenter: parent.verticalCenter
                    source: "../images/image.png"
                }
            }
        }
 }