自适应调整大小的qml文本

6
在学习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
    }
}
}
3个回答

9

1
我查看了这些方法,但出于某种原因,没有效果。 - v_sith_v
@v_sith_v:你能否编辑一下你的问题,包括你尝试使用fontSizeMode属性的内容? - derM
1
我解决了这个问题。你的建议是正确的。谢谢。 - v_sith_v
还有两件事情:font.pointSize(或font.pixelSize)实际上是最大尺寸。字体不会超过这个值。对于非常高的清晰度,请设置一个大值。第二件事是:在表单编辑器中,允许的字体大小的最大值为400。对于更大的值,您将需要使用文本编辑器。 - Uglylab

1
我也遇到了这个问题,但是我发现你只需要将文本项的宽度和高度相对于你想要适配文本的项目/对象(父级)进行设置。以下是一个有效的示例:
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: 如果矩形非常小,由于最小点大小为10,文本可能会溢出。


0

以上答案的问题是,如果您拥有一个可重复使用的字体,并在应用程序中共享它,则如果您设置 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
        }
    }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接