首页 文章

如何制作Flickable确保项目内部的可见性?

提问于
浏览
0

我有一个 Flickable ,其中包含大量的 TextField 对象,这些对象布置在一列中,每个TextField都锚定在前一个TextField的底部 . 一切正常,但是当我使用tab键浏览这些字段时,焦点最终转移到 Flickable 的可见矩形之外的TextField,然后用户无法看到光标,直到它们向下滚动Flickable手动 .

基本上我正在寻找某种“.ensureVisible()”方法,这样当TextField接收到焦点时,Flickable会自动滚动,以便刚刚聚焦的TextField完全可见 .

1 回答

  • 1

    您是否考虑过更具模型性的方法?我的意思是如果你使用 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 而不是flickable,因为后者会给出错误的结果,将当前滚动量考虑在内 . 使用映射将使解决方案与您可能使用的任何定位方案无关,并且还将支持任意级别的嵌套对象 .

相关问题