QML ListView:如何在插入新元素时禁用自动滚动?

问题描述:

有谁知道,当我在头部添加一些元素时,如何防止向下滚动QML ListView?我想以类似Twitter的方式更新ListView,当它始终保持其位置,并且只有显式轻弹是可能的。QML ListView:如何在插入新元素时禁用自动滚动?

您可以使用ListView的currentItemcurrentIndex属性来突出显示新加入的项目或任何要突出显示的项目。

+0

我不想突出显示。我想在currentItem之上插入新的项目而不需要滚动。 –

其实insert功能完成了这项工作。您可以将其插入顶部或任何需要的位置,如modelName.insert(0,{object});。一个可行的例子就在这里。

import QtQuick 1.0 

Rectangle { 
    id: rectangle1 
    width: 320 
    height: 480 

    ListModel { 
     id: cModel 
     ListElement { 
      name: "Bill Smith" 
      number: "555 3264" 
     } 
     ListElement { 
      name: "John Brown" 
      number: "555 8426" 
     } 
     ListElement { 
      name: "Sam Wise" 
      number: "555 0473" 
     } 
    } 
    ListView { 
     id: list_view1 
     width: rectangle1.width 
     height: rectangle1.height - 40 
     anchors.horizontalCenter: parent.horizontalCenter 
     delegate: Text { 
      text: name + ": " + number 
     } 
     model: cModel 
    } 

    Rectangle { 
      id: rectangle2 
      width: 320 
      height: 40 
      color: "#ffffff" 
      anchors.top: list_view1.bottom 

      Text { 
       id: text1 
       text: qsTr("Click to add!") 
       anchors.horizontalCenter: parent.horizontalCenter 
       anchors.verticalCenter: parent.verticalCenter 
       font.pixelSize: 16 
       MouseArea { 
        id: mouse_area1 
        anchors.fill: parent 
        onClicked: addNewItemTop(); 
       } 
      } 
     } 

    function addNewItemTop() 
    { var i = Math.random(); 
     cModel.insert(0,{"name" : "New Number", "number":i.toString()}); 
    } 
    }