自动调整qml中的文本

autoresize text in qml

在学习QML和QtQuick的过程中,出现了如下问题。如何通过减小文本所在的元素来使文本自动减小字体大小。 现在我有了这个方法

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
        }
    }
}

它有效,但不太优雅。也许有一些文本自动调整大小的方法。如果 ColumnLayout 中的换行不起作用。

请帮忙。谢谢

这是我的代码 fontSizeMode 尝试:

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
    }
}
}

使用文本元素 fontSizeMode 属性 设置自动调整大小(Text.HorizontalFitText.VerticalFitText.Fit)。 您可以使用 minimumPixelSize 属性.

调整最小字体大小

详情见http://doc.qt.io/qt-5/qml-qtquick-text.html#fontSizeMode-prop

我也有这个问题,但我想,您只需要相对于 item/object 您想要放置文本的位置(父项)设置文本项的宽度和高度。这是一个工作示例:

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: 如果 rect 非常小,文本可能会因为 minimumPointSize: 10 而挂出。

上述答案的问题在于,如果您设置 font.pixel/pointSize 后在整个应用程序中共享可重复使用的字体,那么它会随处更改,这不是您想要解决的问题,您可以创建一个新字体像这样:

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
        }
    }
}