在以下列表视图的项目中,文本的长度可以不同(10个或1000个字符),因此我想使每个列表视图项目的高度都适合文本高度。(如CSS高度:自动)。
Component {
id: sysNotificationsDelegate
Rectangle {
anchors.left: parent.left
anchors.right: parent.right
height: childrenRect.height
color: "#eee"
Text {
text: model.body // <-- TEXT SIZE CAN BE DIFFERENT
wrapMode: Text.WordWrap
}
}
}
ListView {
anchors.fill: parent
spacing: 10
model: ListModel {
id: listModel
}
delegate: sysNotificationsDelegate
}
Run Code Online (Sandbox Code Playgroud)
什么是实现这一目标的最佳方法?(考虑到我将有很多这样的元素,并且我已经读过qml中的属性绑定具有一些额外的性能成本)
(Qt 5.10)
为了Text能够环绕(或滑动),需要设置宽度,否则宽度将没有限制。
Text 具有3个重要的宽度属性:
width:请考虑它为一行文本的最大宽度,除非您不希望限制屏幕的宽度(可以水平滚动或平移),否则应始终设置该宽度。设置wrapMode或elide不设置width将不起作用。implicitWidth:文本需要占据的宽度才能适合一行。包括左侧和右侧padding。不依赖于显式width。不确定何时使用它\ _(?)_ /¯ 注释中有什么想法吗?contentWidth:考虑到换行和省略,文本实际占据的宽度。不包括左右padding。取决于显式width。用它来查询文本的宽度,例如当您想在某些文本周围绘制一个框时(例如聊天气泡)。高度也存在相同的对应属性。maximumLineCount除了显式之外,还可以限制文本的高度height
这意味着您要执行以下操作:
Rectangle {
anchors.left: parent.left
anchors.right: parent.right
height: text.contentHeight // contentHeight, height and implicitHeight are all the same here since there's no padding, no maximumLineCount and height isn't explicitely set
color: "#eee"
Text {
id: text
text: model.body // <-- TEXT SIZE CAN BE DIFFERENT
width: parent.width // remember, width = max width for Text
wrapMode: Text.WordWrap
}
}
Run Code Online (Sandbox Code Playgroud)