Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Trouble with text alignment



  • I am attempting to get the text to align in the center of this rectangle but despite setting anchors.horizontalCenter too parent.horizontalCenter it is still aligning to the left?

    0_1568746868690_theimage.png

                Rectangle {
                    id: display
                    color: "white"
                    height: componentHeight
                    width: componentWidth
                    radius: 5
    
                    TextStyled {
                        id: entryDisplay
                        elide: Text.ElideRight
                        width: parent.width
                        style: fontStyle
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.bottom: display.bottom
                        color: modelData.settingInvalid ? "red" : "gray"
                        text: ""
                        Component.onCompleted: {
                            if(modelData.settingInvalid)
                            {
                                entryDisplay.text = modelData.value
                                value_container.allowNext = false
                            } else
                            {
                                entryDisplay.text = modelData.value
                            }
                        }
                    }
                }
    

    EDIT: Here is TextStyled:

    Text {
        id: control
    
        property BaseTextStyle style: Style1TextStyle {}
    
        font: control.style.font
        color: control.style.color
    }
    


  • anchors.horizontalCenter centers the whole item inside another, since your TextStyled have same width as rectangle everyting is working fine. You can remove width property or set horizontalAligment: Text.AlignHCenter. It is very useful to add background colored rectangles to an items to see how are they placed:

    Rectangle {
        z: -1
        anchors.fill: parent
        color: "teal"
    }
    

    Add this rectangle at the end of your text element to see how much space occupied by your text item.



  • @intruderexcluder Excellent thank you for that, very insightful!


Log in to reply