如何停止ListView进行“跳转"?更改模型时 [英] How to stop ListView for "jumping" when model is changed
问题描述
我需要做什么:我需要在存储聊天消息的QML中使用ListView
创建一个聊天窗口.我设置listView.positionViewAtEnd()
以便跟踪最后的消息.当我向上滚动时,禁用positionViewAtEnd
以便每次收到新消息时都可以阅读过去的消息而不会在末尾跳转.
What I need to do: I need to create a chat window using a ListView
in QML that stores the chat-messages. I set listView.positionViewAtEnd()
in order to follow the last messages. I disable positionViewAtEnd
when I scroll upwards such that I can read the past messages without jumping at the end every time I receive a new message.
问题:向上滚动后,每次我收到一条新消息时,它都会跳转在列表的开头.为了解决这个问题,我设法存储列表的contentY
,并在每次调用onCountChanged
处理程序时将其重置(请参见下面的代码):
The problem: After scrolling up, every time I receive a new message it jumps at the beginning of list. To solve that I manage to store the contentY
of the list and reset it every time onCountChanged
handler is called (see the code below):
ListView {
id: messagesList
model: contact? contact.messages: []
delegate: delegate
anchors.fill: parent
anchors.bottomMargin: 20
height: parent.height
anchors.margins: 10
property int currentContentY
onMovementEnded: {
currentContentY = contentY
}
onCountChanged: {
contentY = currentContentY
}
onContentYChanged: {
console.log(".....contentY: " + contentY)
}
}
问题在于,即使我设置了上一个contentY
,在更改模型之前,列表仍然会跳一点(几个像素,而不是在结尾处或开头),并且它并不总是跳转.当我转到列表顶部并打印 contentY
时,我会得到负值.从理论上讲,列表开头的contentY
应该是0
.
The problem is that even though I set the last contentY
I had, before the model was changed, the list still jumps a bit (several pixels, not at the end or beginning) and it doesn't jump always. And when I go to the top of the list and print the contentY
I get negative values. Theoretically, contentY
at the beginning of the list should be 0
.
有人可以告诉我出什么事了吗?还是建议使用其他解决方案来创建我的消息列表?
Can somebody tell me what is going wrong? Or maybe suggest another solution to create my message list?
比你提前! :)
推荐答案
一种可能的解决方案是将ListView插入Flickable并为ListView禁用 interactive 标志
One possible solution schould be insert ListView into Flickable and disable interactive flag for ListView
Flickable {
id: fparent
anchors.fill: parent
anchors.bottomMargin: 20
anchors.margins: 10
interactive: true
clip: true
flickableDirection: Flickable.VerticalFlick
contentHeight: messagesList.height
ListView {
id: messagesList
width: parent.width
height: childrenRect.height
clip: true
model: contact? contact.messages: []
delegate: delegate
interactive: false
onCountChanged: {
fparents.returnToBounds();
}
}
}
这篇关于如何停止ListView进行“跳转"?更改模型时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!