qttextfontsqmlqtquick2

Autosizing the pixel size of text based on text length or size using fontSizeMode


I am trying to use fontSizeMode in order to fix a large text in a rectangle.

import QtQuick 2.9
import QtQuick.Window 2.2

Window
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    
    Rectangle
    {
        color: "Red"
        height:50
        width:50

        Text
        {
            text: "Hello"
            fontSizeMode: Text.Fit
            minimumPixelSize: 5
            font.pixelSize: 50 
        }
    }
}

My aim is to shrink the text size if the text is bigger than the rectangle, and a minimum pixel size is given as shown in the program. But the text is not shrinking.

How can I solve this problem?


Solution

  • Use width:parent.width and height:parent.height:

    Window
    {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        
        Rectangle
        {
            color: "Red"
            height: 50
            width: 50
    
            Text { 
                width: parent.width
                height: parent.height
                text: "Hello"
                fontSizeMode: Text.Fit
                minimumPixelSize: 5
                font.pixelSize: 50 
            }
        }
    }