QML ListView: how to disable autoscrolling when inserting new items?

Does anyone know how to prevent QML ListView from scrolling when I add some elements to the head? I want to update the ListView in a Twitter-like style, when it always retains its position and only an explicit click is possible.

+5
source share
2 answers

You can use the ListView currentItemor property currentIndexto select a new item or any item that you want to select.

0
source

In fact, the insert function did the job. You can paste it to the top, or in any desired position, for example modelName.insert(0,{object});. Here is a working example.

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()});
    }
    }
0
source

All Articles