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

QML Text Resized and Centered



  • I am trying to use the ability of Text resizing to fit in an area. However, it does resize, but because both dimensions are defined I cannot center the text in the save area:

    import QtQuick 2.12
    import QtQuick.Window 2.12
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Resized & Centered")
    
        Item {
            id: parametervalue
    
            property string value: "0.00"
        }
    
        Item {
            id: engunits
    
            property string value: "volts"
        }
    
    
        Rectangle {
            id: rect3
    
            width: 100
            height: 33
    
            color: "transparent"
    
            Text {
                anchors.left: rect3.left
                anchors.leftMargin: rect.dropsize*2
                anchors.verticalCenter: rect3.verticalCenter
    
                text: parametervalue.value
    
                width: rect3.width/2
                height: rect3.height
                font.pointSize: 25
                minimumPointSize: 2
                fontSizeMode: Text.Fit
    
                Rectangle {
                    anchors.fill: parent
                    color: "red"
                    opacity: 0.25
                }
            }
    
            Text {
                anchors.right: rect3.right
                anchors.rightMargin: rect.dropsize
                anchors.verticalCenter: rect3.verticalCenter
    
                text: engunits.value
    
                width: rect3.width/3
                height: rect3.height
                font.pointSize: 25
                minimumPointSize: 2
                fontSizeMode: Text.Fit
    
                Rectangle {
                    anchors.fill: parent
                    color: "blue"
                    opacity: 0.25
                }
            }
        }
    }
    

    If the string is short then it won't be centered in the horizontal direction. If the text is long it won't be centered in the vertical direction. I have to assume there is a way to do what I want that I am overlooking.



  • Doh, another post had an example of what I wanted:

    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    

Log in to reply