簡體   English   中英

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

[英]How to increase height of Rectangle according to text in QML

我無法增加環繞可以動態更改的文本項目(例如聊天消息)的矩形(或 RowLayout)的高度。

我嘗試了很多方法(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
            }
        }
    }
}

}

您必須為Rectangle (以及Item指定implicitHeightimplicitWidth Rectangle )。

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

        Text {
            id: element
            anchors.fill: parent
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignLeft
            wrapMode: Text.WordWrap
            clip: false
            font.pixelSize: 12
        }
    }

請注意,您當前使用anchors.margins設置在這里略有沖突,因為這不計入implicitHeight / Width ,所以我將它們排除在外。


另一種選擇是Label (來自QtQuick.Controls )的background設置為您想要的Rectangle ,然后將其正確拉伸:

 Label {
      leftPadding: 10
      rightPadding: 10
      ...

      background: Rectangle {
          color: "green"
      }
 }

在我看來,這將使您更容易控制文本的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM