'autoresize text in qml
In the process of studying QML and QtQuick, the following question arose. How can I make the text automatically reduce the font size by decreasing the element in which it is located. Now I have this method
Rectangle {
id: main_window
width: 700
height: 500
property int main_w: main_window.width
Rectangle {
width: 400
height: 400
anchors.centerIn: parent
color: 'green'
Text {
text: "SIZE ME!!!"
anchors.centerIn: parent
color: 'white'
font.pointSize: {
if (main_window.main_w < main_window.width)
return main_window.main_w / 35 // we need 20pt
return main_window.width / 35
}
visible: {
if (parent.width < 100)
return false
return true
}
}
}
It works, but not too elegantly. Maybe there are some methods that the text automatically resized. If the wrap in the ColumnLayout does not work.
Please help. Thank you
Here my code with fontSizeMode trying:
Rectangle {
id: root
width: 700
height: 700
property int mrg: 10
Rectangle {
anchors.centerIn: parent
width: 400
height: 400
color: 'green'
Text {
id: field
text: "Size me!"
minimumPointSize: 10
font.pointSize: 60
fontSizeMode: Text.Fit
color: 'white'
anchors.centerIn: parent
}
}
}
Solution 1:[1]
I have this problem too, but figured, that you need only set the width and height of the Text item relative to the item/object where you want the text fitted (parent). Here is a working example:
import QtQuick 2.7
Rectangle {
id: root
width: 700
height: 700
property int mrg: 10
Rectangle {
anchors.centerIn: parent
width: root.width * 0.5
height: root.height * 0.5
color: 'green'
Text {
id: field
width: parent.width
height: parent.height
text: "Size me!"
minimumPointSize: 10
font.pointSize: 60
fontSizeMode: Text.Fit
color: 'white'
anchors.centerIn: parent
}
}
}
PS: If the rect is very small, text could be hanging out because of the minimumPointSize: 10.
Solution 2:[2]
Problem with the above answers is that if you have a reusable font that you share across your app if you set font.pixel/pointSize it will be changed everywhere which is not wanted to solve that you can create a new font like this:
import QtQuick
Rectangle {
id: root
width: 700
height: 700
property int mrg: 10
Rectangle {
anchors.centerIn: parent
width: root.width * 0.5
height: root.height * 0.5
color: 'green'
Text {
id: field
width: parent.width
height: parent.height
text: "Size me!"
color: 'white'
font: Qt.font({
bold: true,
underline: false,
pixelSize: field.width / 10, // resize relative to parent
family: Theme.fFamily,
})
anchors.centerIn: parent
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ãdám R. |
| Solution 2 | TOHO |
