我创建了一个简单的可重复示例来实现我想要实现的目标。 ListView 动态填充字符串,只要有新内容就可以向下滚动内容。 但它并没有按预期工作。
import QtQuick 2.15
import QtQuick.Controls 2.5
import QtQuick.Layouts 6.3
Page{
Connections{
target: recipeFetcher
}
ListView {
width: parent.width
height: parent.height
id: listView
model: ListModel {
id: recipeModel
}
delegate: Column {
anchors.fill: parent
spacing: 10
Text {
Layout.fillHeight: true
width: parent.width - 20
wrapMode: Text.Wrap
text: model.titleText
color: "white"
horizontalAlignment: Text.AlignHCenter
}
Text {
Layout.fillHeight: true
width: parent.width - 20
wrapMode: Text.Wrap
text: model.ingredientsText
color: "orange"
horizontalAlignment: Text.AlignHCenter
}
Text {
Layout.fillHeight: true
width: parent.width - 20
wrapMode: Text.Wrap
text: model.instructionsText
color: "blue"
horizontalAlignment: Text.AlignHCenter
}
}
ScrollBar.vertical: ScrollBar {
id: scrollbar
size: listView.contentHeight / listView.height
policy: ScrollBar.AlwaysOn
contentItem: Rectangle {
implicitWidth: 5
color: "orange"
radius: width
}
}
Component.onCompleted: {
var strings = [['a'.repeat(3000), 'b'.repeat(3000), 'c'.repeat(3000)], ['a'.repeat(3000), 'b'.repeat(3000), 'c'.repeat(3000)], ['a'.repeat(3000), 'b'.repeat(3000), 'c'.repeat(3000)]]
for (var i = 0; i < strings.length; ++i) {
recipeModel.append({titleText: strings[0] + "\n\n", ingredientsText: strings[1] + "\n\n", instructionsText: strings[2] + "\n\n"});
}
console.log(listView.contentHeight)
}
}
}
当您开始向下滚动时,不会有更多字符附加到 listView,只是什么都没有,空白页面。
将字符串附加到模型后,由于某种原因,listView 的 contentHeight 也为 0。
要自定义
ScrollBar
,请参阅自定义 ScrollBar 文档。
并且将 ScrollBar
附加到 ListView
时,无需手动设置 size
属性。
当滚动条附加到可轻拂对象时,会自动配置此属性。 滚动条文档
还有
anchors.fill: parent
中使用 delegate
。Layout.fillHeight
对Column
没有影响;考虑使用 ColumnLayout
代替。 ColumnLayout 文档padding
,而不是从项目的 width
中减去它。QtQuick.Controls.Basic
而不是 QtQuick.Controls
。 定制非原生风格import QtQuick
import QtQuick.Controls.Basic
Page {
id: root
implicitWidth: 400
implicitHeight: 290
ListView {
id: listView
anchors.fill: parent
model: ListModel {
Component.onCompleted: {
for (var i = 0; i < 10; ++i) {
append({
titleText: 'titleText,'.repeat(100),
ingredientsText: 'ingredientsText,'.repeat(100),
instructionsText: 'instructionsText,'.repeat(100)
});
}
}
}
delegate: Column {
required property string titleText
required property string ingredientsText
required property string instructionsText
spacing: 5
padding: 5
rightPadding: listView.ScrollBar.vertical.width
width: listView.width - leftPadding - rightPadding
Repeater {
model: [titleText, ingredientsText, instructionsText]
Label {
width: parent.width
text: modelData
color: ['#2af','#fac','#da5'][index];
wrapMode: Text.Wrap
horizontalAlignment: Text.AlignHCenter
}
}
}
ScrollBar.vertical: ScrollBar {
id: scrollbar
contentItem: Rectangle {
radius: 2
implicitWidth: 10
implicitHeight: 100
color: 'gray'
}
}
}
}