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

How to auto size font on TextInput or TextField?



  • Hello,

    using TextInput in customized Combocox, I want the text adjusted following content.

    Original code is:

    Rectangle{
            width:control.width-control.indicator.width
            height:control.height
            anchors.left:control.left
            color:"transparent"
            border.width:1
            border.color:"black"
            radius: 2
            clip: true
            TextInput {
                id:textInputItem
                anchors.fill:parent
                focus: true
                activeFocusOnPress: true
                activeFocusOnTab: true
                padding : 5
                rightPadding: 5
                color: "black"
                leftPadding: 5
                selectByMouse: true
                text: control.displayText
                font.pixelSize:20
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
            }
        }
    

    I tryed many solution like onTextChanged: {scale= Math.min(1, width/contentWidth)} or
    onTextChanged: {font.pixelSize= Math.min(1, width/contentWidth)} but the size not change all the time, don't know why and scale change text size but also text width, then all text is not visible, that not solving the problem...

    Could you help me?

    Thanks a lot



  • @filipdns here is what I did waiting better solution...

    FontMetrics  {
                id: textMetrics
                font.pixelSize:20
            }
            TextInput {
                id:textInputItem
                anchors.fill:parent
                focus: true
                activeFocusOnPress: true
                activeFocusOnTab: true
                padding : 5
                rightPadding: 5
                color: "black"
                leftPadding: 5
                selectByMouse: true
                text: control.displayText
                font.pixelSize:20
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                onTextChanged: { font.pixelSize=20*Math.min(1,width/(textMetrics.advanceWidth(text)*1.4));textMetrics.font.pixelSize=font.pixelSize}
            }
    

Log in to reply