将它们添加到列表视图时如何保持最后一个项目在视图中?
How to keep last items in view when adding them to listview?
我有一个 ListView,我可以在其中动态添加 ListElements。 ListView最多有10个项目可以在视图中,所以我也有一个ScrollBar。当我添加第 11 个以上的项目时,我总是希望它滚动到视图中。
ListView {
id: logListView
delegate: logListViewDelegate
model: logListModel
anchors.fill: parent
ScrollBar.vertical: ScrollBar {}
}
ListModel {
id: logListModel
}
Component {
id: logListViewDelegate
Item {
height: 44
width: logListView.width
Text {
id: countText
width: 18
font {
pixelSize: 16
family: variables.globalFont
}
color: colors.foregroundColor3
text: index+1
anchors {
left: parent.left
leftMargin: 7
verticalCenter: parent.verticalCenter
}
}
Text {
id: timeText
width: 96
horizontalAlignment: Text.AlignRight
font {
pixelSize: 24
family: variables.globalFont
}
color: colors.foregroundColor1
text: time
anchors {
left: countText.right
verticalCenter: parent.verticalCenter
}
}
Text {
id: unitText
width: 18
font {
pixelSize: 16
family: variables.globalFont
}
color: colors.foregroundColor3
text: unit
anchors {
left: timeText.right
leftMargin: 6
bottom: timeText.bottom
bottomMargin: 2
}
}
}
}
我在列表视图之外有一个按钮,单击它时:
logListModel.append({
time: myTime, unit: myUnit
})
新项目刚添加到列表底部,当超过 10 个时隐藏。添加项目时,我希望列表自动滚动到它。
在您的 ListView
中,通过在调用 onCountChanged
时更改 currentIndex 滚动到底部(当您的模型已更改时):
ListView {
id: logListView
delegate: logListViewDelegate
model: logListModel
anchors.fill: parent
ScrollBar.vertical: ScrollBar {}
onCountChanged: {
var newIndex = count - 1 // last index
positionViewAtEnd()
currentIndex = newIndex
}
}
我有一个 ListView,我可以在其中动态添加 ListElements。 ListView最多有10个项目可以在视图中,所以我也有一个ScrollBar。当我添加第 11 个以上的项目时,我总是希望它滚动到视图中。
ListView {
id: logListView
delegate: logListViewDelegate
model: logListModel
anchors.fill: parent
ScrollBar.vertical: ScrollBar {}
}
ListModel {
id: logListModel
}
Component {
id: logListViewDelegate
Item {
height: 44
width: logListView.width
Text {
id: countText
width: 18
font {
pixelSize: 16
family: variables.globalFont
}
color: colors.foregroundColor3
text: index+1
anchors {
left: parent.left
leftMargin: 7
verticalCenter: parent.verticalCenter
}
}
Text {
id: timeText
width: 96
horizontalAlignment: Text.AlignRight
font {
pixelSize: 24
family: variables.globalFont
}
color: colors.foregroundColor1
text: time
anchors {
left: countText.right
verticalCenter: parent.verticalCenter
}
}
Text {
id: unitText
width: 18
font {
pixelSize: 16
family: variables.globalFont
}
color: colors.foregroundColor3
text: unit
anchors {
left: timeText.right
leftMargin: 6
bottom: timeText.bottom
bottomMargin: 2
}
}
}
}
我在列表视图之外有一个按钮,单击它时:
logListModel.append({
time: myTime, unit: myUnit
})
新项目刚添加到列表底部,当超过 10 个时隐藏。添加项目时,我希望列表自动滚动到它。
在您的 ListView
中,通过在调用 onCountChanged
时更改 currentIndex 滚动到底部(当您的模型已更改时):
ListView {
id: logListView
delegate: logListViewDelegate
model: logListModel
anchors.fill: parent
ScrollBar.vertical: ScrollBar {}
onCountChanged: {
var newIndex = count - 1 // last index
positionViewAtEnd()
currentIndex = newIndex
}
}