如何用QML在矩形中包装一些文本?

问题描述 投票:0回答:2

我必须执行一个非常简单的任务:我想在矩形内显示一段文本,该矩形的大小应该恰好是文本的宽度。

在C ++中,它很容易做到。只需定义QString并应用QFontMetrics即可获得其宽度。然后定义矩形图形元素以具有该大小。它在五分钟内完成。

我听说QML更容易使用。因此,我期待在不到五分钟的时间内解决这个问题。我没有,我仍然坚持下去。这是我尝试过的:

Rectangle {
    width: myText.contentWidth
    height: myText.contentHeight

    Text {
        anchors.fill:parent
        id: myText
        font.family: "Helvetica"
        font.pointSize: 50
        text:  qsTr("The string I want to display")
    }
}

由于某些我不明白的原因,这不起作用。我找到了一种方法,以一种不完全符合我需要的方式来做:

Rectangle {
    width: 100
    height: 100

    MouseArea {
       id: myMouseArea
       anchors.fill: parent
       onClicked: parent.width=myText.contentWidth 
       hoverEnabled: true
     }

    Text {
        anchors.fill:parent
        id: myText
        font.family: "Helvetica"
        font.pointSize: 50
        text:  qsTr("The string I want to display")
    }
}

在这种情况下,当我单击矩形时,它获得正确的宽度。不过,我对这个解决方案不感兴趣,因为我不想点击得到一个正确大小的矩形。

我希望每当myText改变文本时,矩形的大小都会得到正确的大小。在Text项中使用onTextChanged也不起作用。

我在这里错过了什么?

text qml textwrapping
2个回答
3
投票

据我所知,在Qt 5.4中,开发人员可以使用Font指标,因此它们在QML中相对较新。你主要得到FontMetricsTextMetrics。一个简单的用法示例:

import QtQuick 2.4
import QtQuick.Window 2.2

Window {
    visible: true
    width: 280; height: 150

    TextMetrics {
        id: textMetrics
        font.family: "Arial"
        font.pixelSize: 50
        text: "Hello World"
    }

    Rectangle {
        width: textMetrics.width
        height: textMetrics.height
        color: "steelblue"

        Text {
            text: textMetrics.text
            font: textMetrics.font
        }
    }
}

正如Phrogz所述,TextMetrics类型不支持测量包装文本。


0
投票

我确定Label组件可以完成这项工作:

import QtQuick 2.1
import QtQuick.Controls 2.4

ApplicationWindow {
    visible: true

    Column {
        Repeater {
            model: [
                {"color": "red", "radius": 1},
                {"color": "green", "radius": 2},
                {"color": "blue", "radius": 3}
            ]
            Label {
                padding: 0
                text: modelData.color
                font.family: "Helvetica"
                font.pointSize: 50
                background: Rectangle {
                   color: modelData.color
                   radius: modelData.radius
                }
            }
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.