Home > database >  anchor.centerIn doesn't work as expected in my case
anchor.centerIn doesn't work as expected in my case

Time:12-27

I'm creating a component in QML, works fine but I want the TEXT field to be in the center of rectangle. For that I've anchored it accordingly but the anchor doesn't work. I don't know why.

Item {

    id: root

    property int main_rect_height: 32
    property int elem_txt_size: 14
    property string elem_border_color: "red"
    property int elem_width: parent.width/6.5

    Rectangle {
        id: clients_rect
        width: root.parent.width-27
        height: main_rect_height
        color: "transparent"
        border.color: "black"

        Rectangle {
            id: username_rect
            width: elem_width
            height: parent.height
            color: "transparent"
            border.color: elem_border_color
            Text {
                id: username_txt
                text: "USERNAME"
                font.pixelSize: elem_txt_size
                anchors {
                    fill: parent
                    centerIn: parent    // THIS DOESN'T WORK!
                }
            }
        }
}

CodePudding user response:

By using anchors.fill: parent, you're setting the size and position of the Text object to match the parent. Centering an object of the same size won't do anything because it already takes up the entire space of the parent. And by default, the text is aligned to the top and left. You have two options:

  1. You can use Text's alignment properties to align the text within itself to be centered:
Text {
    anchors.fill: parent
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
}
  1. Or, you can simply use centerIn without the fill.
Text {
    anchors.centerIn: parent
}
  • Related