你有沒有考慮更多的模型ar方法呢?我的意思是,如果您使用類似ListView
的東西,您可以簡單地更改currentItem
,此時如果視圖超出可見範圍,視圖將自動滾動至該視圖。
此外,它只會加載可見範圍內的文本元素,並保存在某些內存中。
但即使採用您目前的方法,也不會那麼複雜以確保可視性。
Flickable {
id: flick
anchors.fill: parent
contentHeight: col.height
function ensureVisible(item) {
var ypos = item.mapToItem(contentItem, 0, 0).y
var ext = item.height + ypos
if (ypos < contentY // begins before
|| ypos > contentY + height // begins after
|| ext < contentY // ends before
|| ext > contentY + height) { // ends after
// don't exceed bounds
contentY = Math.max(0, Math.min(ypos - height + item.height, contentHeight - height))
}
}
Column {
id: col
Repeater {
id: rep
model: 20
delegate: Text {
id: del
text: "this is item " + index
Keys.onPressed: rep.itemAt((index + 1) % rep.count).focus = true
focus: index === 0
color: focus ? "red" : "black"
font.pointSize: 40
onFocusChanged: if (focus) flick.ensureVisible(del)
}
}
}
}
該解決方案是快速和糟糕的,但將它放入生產形狀將是微不足道的。重要的是映射到contentItem
而不是可滑動的,因爲後者會給出錯誤的結果,並將當前滾動的數量考慮在內。使用映射可以使解決方案不受你可能使用的任何定位方案的影響,還可以支持任意級別的嵌套對象。