Qt 如何根据QML中的文本增加矩形的高度

Qt 如何根据QML中的文本增加矩形的高度,qt,qml,Qt,Qml,我无法增加环绕文本项的矩形(或行布局)的高度,这些文本项可能会动态变化(例如聊天信息) 我尝试了很多方法(Text.paintedHeight,childrenRect…),但当文本被包装时,一切看起来都很奇怪 我的目标是显示聊天信息,根据其包装文本高度拉伸它们 谢谢你的意见 import QtQuick 2.0 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.0 ApplicationWindow { visible: true w

我无法增加环绕文本项的矩形(或行布局)的高度,这些文本项可能会动态变化(例如聊天信息)

我尝试了很多方法(Text.paintedHeight,childrenRect…),但当文本被包装时,一切看起来都很奇怪

我的目标是显示聊天信息,根据其包装文本高度拉伸它们

谢谢你的意见

import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
visible: true

width: 900
height: 500

ColumnLayout {
    width: parent.width
    spacing: 2

    RowLayout {
        id: rowLayout
        spacing: 3

        Rectangle {
            height: 50
            width: 50
            color: "red"
        }

        Rectangle {
            id: rectangle
            width: 50
            color: "green"
            Layout.fillHeight: true
            Layout.fillWidth: true

            Text {
                id: element
                text: "If the GridLayout is resized, all items in the layout will be rearranged. It is similar to the widget-based QGridLayout. All visible children of the GridLayout element will belong to the layout. If you want a layout with just one row or one column, you can use the RowLayout or ColumnLayout. These offer a bit more convenient API, and improve readability.\n\nBy default items will be arranged according to the flow property. The default value of the flow property is GridLayout.LeftToRight.\n\nIf the columns property is specified, it will be treated as a maximum limit of how many columns the layout can have, before the auto-positioning wraps back to the beginning of the next row. The columns property is only used when flow is GridLayout.LeftToRight."
                anchors.rightMargin: 10
                anchors.leftMargin: 10
                anchors.fill: parent
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignLeft
                wrapMode: Text.WordWrap
                clip: false
                font.pixelSize: 12
            }
        }
    }
}

}您必须为
矩形
指定
隐式宽度
隐式宽度
(以及

请注意,您当前的设置与
锚点.边距
在这里有点冲突,因为这不计入
隐式宽度
/
中,所以我将其忽略


另一个选项是将
标签
(从
QtQuick.Controls
)的
背景设置为所需的
矩形
,然后适当拉伸:

 Label {
      leftPadding: 10
      rightPadding: 10
      ...

      background: Rectangle {
          color: "green"
      }
 }

在我看来,这将使你更容易控制你的文字的位置

我用第一种方法成功了,可能也会尝试第二种方法。这是推荐的方法,似乎要完成很多工作,一个简单的任务。。但是谢谢你,在第二种方法中,你不必到处添加填充物,我发现这样做的工作量更少。此外,您还可以将一个标签+背景/矩形的完整设计放在它自己的qml文件中,使其非常可移植。您想将矩形调整为文本大小吗?我看到你有宽度为50的
,如果文本是一个字母(或表情符号),该怎么办?您希望矩形仍为50宽,还是希望它更小,并且50更大,是文本应换行的最大宽度?该“宽度:50”为打字错误,在其下方三行被布局覆盖。fillWidth:true,因此其被忽略。目标是让矩形填充整行,第一个矩形表示图标。我对增加高度感兴趣,当包含太长的文本时,宽度由fillWidth负责,但当存在较长的文本时,矩形并没有增加其高度。
 Label {
      leftPadding: 10
      rightPadding: 10
      ...

      background: Rectangle {
          color: "green"
      }
 }