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

[Partially solved] QML Text seems to be horizontally aligned wrong



  • I'm trying to make a button with centered text inside, but I have a following problem:
    !http://s15.postimage.org/pnmyox5yv/Screenshot_at_2012_08_17_12_20_56.png(misaligned text)!
    As you can see, the Text element is centered correctly (its dimensions are shown by the black frame), but the real text inside it is painted a bit left. It doesn't depend on font. What should I do to make it centered correctly?
    Code:
    @ Text {
    id: label
    text: toplevel.text
    font.pixelSize: toplevel.height * 0.4
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.baseline: alignRect.bottom
    }
    Item {
    id: alignRect
    visible: false
    anchors.centerIn: parent
    width: 10
    height: label.font.pixelSize
    }
    Rectangle {
    color: "transparent"
    border.width: 1
    anchors.fill: label
    }@


  • Moderators

    Try this:
    @
    Text {
    id: label
    text: toplevel.text
    font.pixelSize: toplevel.height * 0.4
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.baseline: alignRect.bottom

        // this:
        width: paintedWidth
        height: paintedHeight
        // and this:
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
    }
    

    @



  • Thank you, it helped a bit - now the text is less misaligned!
    !http://s14.postimage.org/dfyjzpwfx/Screenshot_at_2012_08_17_13_47_35.png(new result)!
    But it isn't the ideal result yet :(


  • Moderators

    Add anchor margins :)



  • Yeah, that dirty way should work, but isn't there a clean way to do this and why does this stuff happen?


  • Moderators

    Glyph painting is a very hard job in general. Ultimately, that is probably a Qt bug, or type bug (glyph definition). You have to remember, that some letters are allowed to go beyond their registered space (take a 'y' for example, in some types, and especially in handwriting, it often even obscures other letters), others are allowed to join, etc.

    I had that problem in my code, too, I've added the aligning as above + adjusted the margins by hand. It seems to be working well, even during scaling, and on different operating systems.


Log in to reply