Search code examples
qml

QML Rowlayout how to center text fields


I need to display year, month and day in separate fields.

I can at least manage the output using rowlayout and text fields.

enter image description here

What is the best way to get the individual fields closer together without setting fixed widths?

Ideally, the construct should then be displayed centred in the rectangle (picture 2).

enter image description here

Rectangle { id: root; width: 300; height: 100
    
    RowLayout { anchors.fill: parent; spacing: 0; 
        Text { text: "2023" }
        Text { text: ":" }
        Text { text: "07" }
        Text { text: ":" }
        Text { text: "28" }
    }
}

Solution

  • You should not have the RowLayout fill the Rectangle, but center it:

    Rectangle { id: root; width: 300; height: 100
    
        RowLayout { 
            anchors.horizontalCenter: parent.horizontalCenter;
            anchors.top: parent.top
            anchors.bottom: parent.bottom
    
            spacing: 0; 
    
            Text { text: "2023" }
            Text { text: ":" }
            Text { text: "07" }
            Text { text: ":" }
            Text { text: "28" }
        }
    }