Search code examples
qttextqmlcenter

Center Text QML type based on the dot of a decimal number


I've got a simple Text QML type:

Item {
    anchors.fill: parent

    Text {
        id: centerText
        text: "6.9"
        anchors.horizontalCenter: parent.horizontalCenter
        y: 570
    }
}

Currently, the Text will be centered based on the whole length of the string. But I would like to center the Text based on the dot character.

I was thinking of splitting the actual Text in three parts: the round part, the dot and the decimal part. However I don't think I could split the float variable to only get the decimal part.

Is there another way more convenient and adapted to QML?


Solution

  • Here is a quick example how you can achieve that. The "dummy" hidden text is used to measure how wide the integer part of the number is, obtained by using Math.floor(). Then you simply position it so that the decimal point is always in the center of the parent object regardless of what the number is.

     Column {
        x: 100
        y: 200
        spacing: 5
        Slider {
          id: sl
          width: 400
          minimumValue: 0
          maximumValue: 100
        }
        Rectangle {
          width: 400
          height: 100
          Text {
            x: parent.width * .5 - dummy.width
            y: parent.height * .5 - height * .5
            text: sl.value
            Text {
              id: dummy
              text: Math.floor(sl.value)
              visible: false
            }
          }
        }
      }
    

    enter image description here

    BTW, when you have anchors.fill: parent then anchors.bottom: parent.bottom is redundant.