trudesagen
trudesagen

Reputation: 57

In ListView, how can you set the currentIndex or currentItem to a dynamically created element?

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)
            }
        }
    }
}

Upvotes: 1

Views: 1885

Answers (1)

JarMan
JarMan

Reputation: 8287

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

ListView {
    ...

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

Upvotes: 2

Related Questions