0
votes

I got a listview with a c++ listmodel and a rectangle with a mousarea as delegate. Internally in my code, my listmodel gets data appended, and I do

beginResetModel();
list.append(element);
endResetModel();

My model updates and the element appears just fine, but I am not able to set the currentIndex to the newly created item.

I am trying to use Component.onCompleted inside the delegate like this

Component.onCompleted:   {
    ListView.currentIndex = index;
    console.log("Show List: ", ListView.currentIndex, index);
}

But the index in the log output says the currentIndex doesn't change after I set it to my models index.

I do the same inside my mousearea, in onClicked, and there it works fine.

How can I make my newly created listview element the currentItem/currentIndex?

I am using this currentIndex to change the color of the created element (this is inside my rectangle delegate)

color: ListView.currentIndex == index ?  "lightred" : "darkred"

Are there better ways of going about what I am trying to do possibly?

Full code example below:

ListView {
    id: listView
    focus: true
    clip: true
    model: listModel
    delegate: Rectangle {
        id: listDelegate
        color: listView.currentIndex == index ?  "green" : "red"
        height: 20
        width: 100
        radius: 2
        Component.onCompleted:   {
            listView.currentIndex = index
            console.log("Show List: ", listView.currentIndex, index)
        }
        MouseArea {
            anchors.fill: parent
            onClicked: {
                listView.currentIndex = index
                console.log("onClicked: ", listView.currentIndex, index)
            }
        }
    }
}
1
Does the new item always get added to the end?JarMan
Are there better ways of going about what I am trying to do possibly? You can add a signal in your C++ code that will be emitted every time a new element is added to the list. Such a signal would be caught in QML and provide reliable information that some element were actually added. Otherwise, there is a risk that one day some element will be removed from the list and that removal will spark also all proposed slots like Component.onCompleted or any other.pklimczu
Currently it only gets added to the end with append, but that might change in the future, so the solution will work for now but I have to look into other solutions.trudesagen

1 Answers

2
votes

You can just check for when the count changes, like this:

ListView {
    ...

    onCountChanged: {
        listView.currentIndex = listView.count - 1;
    }
}