2017-08-29 63 views
0

我有一個Flickable,其中包含大量的TextField對象,每個TextField都固定在上一個TextField的底部。一切工作正常,除了當我使用Tab鍵瀏覽這些字段時,最終焦點會轉到位於Flickable的可見矩形外部的TextField,然後用戶無法看到光標,直到它們向下滾動Flickable手動。如何使Flickable確保項目內部的可見性?

本質上我正在尋找某種「.ensureVisible()」方法,這樣當TextField接收到焦點時,Flickable會自動滾動,這樣才能使焦點集中的TextField完全可見。

回答

1

你有沒有考慮更多的模型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而不是可滑動的,因爲後者會給出錯誤的結果,並將當前滾動的數量考慮在內。使用映射可以使解決方案不受你可能使用的任何定位方案的影響,還可以支持任意級別的嵌套對象。

相關問題