我无法增加可以动态更改的文本项目(例如聊天消息(周围的矩形(或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.nnBy default items will be arranged according to the flow property. The default value of the flow property is GridLayout.LeftToRight.nnIf 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
(指定implicitHeight
和implicitWidth
。
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
的background
(从QtQuick.Controls
(设置为所需的Rectangle
,然后将其正确拉伸:
Label {
leftPadding: 10
rightPadding: 10
...
background: Rectangle {
color: "green"
}
}
在我看来,这会让你更容易控制文本的位置。