我有以下 ListView
,当在 C++ 端使用 setStringList
更新 QStringListModel
时,它始终显示列表的开头。
例如,用户可以在 View 中上下滚动,当模型更新时, View 将返回到列表的开头。
如何禁用此行为?
我还需要 View 一次精确显示 X 个项目(在我的示例中为 2 个)。该 View 本身不可滚动( interactive: false
),但用户可以通过单击 UI 中某处的上下 Button
来导航列表。
有合适的方法吗? (关注Is it possible to show only certain indexes of a QML listview?)
编辑:我为“上/下”问题添加了 2 个函数,它似乎按预期工作,但我仍然很想知道是否有更好的方法。
谢谢。
ListView {
id: view
anchors.top = parent.top
anchors.left = parent.left
readonly property int visibleItems: 2
readonly property int itemHeight: 20
height: visibleItems * itemHeight
width: 100
clip: true
model: listModel // a QStringListModel
delegate: Rectangle {
border.width: 1
border.color: "black"
height: view.itemHeight
width: 100
Text { text: model.display }
}
interactive: false
function up() {
var currentTopIndex = indexAt(view.width / 2, contentY)
if (currentTopIndex !== -1) {
var newTopIndex = currentTopIndex - view.visibleItems
if (newTopIndex >= 0)
view.positionViewAtIndex(newTopIndex, ListView.Beginning)
}
}
function down() {
var currentTopIndex = indexAt(view.width / 2, contentY)
if (currentTopIndex !== -1) {
var newTopIndex = currentTopIndex + view.visibleItems
if (newTopIndex < view.count)
view.positionViewAtIndex(newTopIndex, ListView.Beginning)
}
}
最佳答案
将其添加到您的 ListView
中,每当模型数据发生更改时,您都会重置 contentY
属性。这里我假设 contentX
没有改变。
property real previousContentY
Connections {
target: model
onModelAboutToBeReset: view.previousContentY = view.contentY
onModelReset: view.contentY = view.previousContentY
}
如果您只想显示某些项目,您可能还需要添加 snapMode: ListView.SnapToItem
。
关于c++ - 模型更新时 QML ListView 默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56671191/