Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoresize text in qml

Tags:

qt

qml

qtquick2

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
    }
}
}
like image 757
v_sith_v Avatar asked Jun 05 '17 07:06

v_sith_v


People also ask

How do you center text in QML?

If you want the text to be, say, centered in its parent, then you will need to either modify the Item::anchors, or set horizontalAlignment to Text. AlignHCenter and bind the width to that of the parent.

What is text in QML?

The Text item allows you to add formatted text to a scene. More... Inherits Item. This element was introduced in Qt 4.7.


1 Answers

Use the Text elements fontSizeMode property to set autosizing (Text.HorizontalFit, Text.VerticalFit or Text.Fit). You can adjust the minimum font size with minimumPixelSize property.

See http://doc.qt.io/qt-5/qml-qtquick-text.html#fontSizeMode-prop for details

like image 136
onion Avatar answered Oct 02 '22 00:10

onion