How to adjust text font size relative to parent
Solved
QML and Qt Quick
-
Re: [solved] How to make Text font size to be auto adjusted
QtObject{ readonly property font defaultFont: Qt.font({ pixelSize: 19 }) } Text { width: parent.width height: parent.height font: defaultFont font.pointSize: 100 // will cause an error minimumPointSize: 10 fontSizeMode: Text.Fit }
The refferenced topic shows how to fit a text inside a parent but wont cover if the font is a
readonly
property
which is very useful to save your fonts in one place and copy theme threw the app..
as you may know Text wont provide the maximum equivalent ofminimumPointSize
, so how to overcome this? -
I have found two possible solution:
- instead of creating a font property we can create our custom
Text
and setting the font corresponding to the parent size like this:
import QtQuick Text{ property real pixelSize: Theme.fPixelSizeS property bool bold: false property string fontFamily: Theme.fFamily property real minPixelSize: 10 property font _font _font.pixelSize: pixelSize _font.family: fontFamily _font.bold: bold color: Theme.textDefault font: _font anchors.verticalCenter: parent.verticalCenter wrapMode: Text.WordWrap fontSizeMode: Text.HorizontalFit; elide: Text.ElideMiddle }
- create a binding to the Qt.font function and provide our defaults as primitives like this:
QtObject{id: defaults readonly property string fFamily: "Segoe UI Semibold" } Text {id: someText width: parent.width height: parent.height font: Qt.font({ pixelSize: someText.height / 5, fontFamily: defaults.fFamily }) minimumPointSize: 10 fontSizeMode: Text.Fit }
note that the second approach for some reason makes the console very chatty.
- instead of creating a font property we can create our custom