Home > Mobile >  Scale Qml button text depending on button size
Scale Qml button text depending on button size

Time:10-03

I want to to scale a button's text with respect to its height:

import QtQuick 2.11
import QtQuick.Controls 2.10

ToolButton {
    id: btn
    font.pixelSize: implicitHeight*0.8 // Binding loop detected for property "font.pixelSize"
    
    contentItem: Text {
        text: btn.text
        font: btn.font
    }
}

This sometimes works but more often a binding loop is detected because when the font size changes, also the button size changes. What is the correct way for scaling the text size?

Regards,

CodePudding user response:

Use "height" instead of "implicitHeight".

And the ToolButton's height is bound to the font size by default, so you need to set a height for your button.

CodePudding user response:

A cheat to avoid the binding loop is to use imperative JavaScript code, e.g.

import QtQuick 2.15
import QtQuick.Controls 2.15

Page {
    anchors.fill: parent
    ToolButton {
        id: btn
        anchors.fill: parent
        text: qsTr("Hello")
        onHeightChanged: Qt.callLater( () => { font.pixelSize = height* 0.8 } )

        contentItem: Text {
            text: btn.text
            font: btn.font
        }
    }
}

You can Try it Online!

  • Related