Scale Qml button text depending on button size

741 Views Asked by At

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,

2

There are 2 best solutions below

4
Rawen On

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.

0
Stephen Quan On

One method to avoid the binding loop is not use declarative code but imperative instead. For this, we watch for onWidthChanged and onHeightChanged and invoke resize(). Our resize routine we compute a scale using a fixed TextMetric at a reference font size. With that we can size the text accordingly:

import QtQuick 2.15
import QtQuick.Controls 2.15

Page {
    anchors.fill: parent

    ToolButton {
        id: btn
        anchors.centerIn: parent
        width: parent.width / 2
        height: parent.height / 2
        text: qsTr("Hello")
        property TextMetrics tm: TextMetrics {
            font.pixelSize: 20
            text: btn.text
        }
        onWidthChanged: Qt.callLater(resize)
        onHeightChanged: Qt.callLater(resize)
        function resize() {
            let fx = width / tm.width * tm.font.pixelSize * 0.8;
            let fy = height / tm.height * tm.font.pixelSize * 0.8;
            font.pixelSize = Math.min(fx, fy)
        }
    }
}

You can Try it Online!