ListView select item by code
-
What do you mean under 'select'? If you want to highlight it you can set delegate background:
ListView { ... delegate: ItemDelegate { ... background: Rectangle { ... visible: ListView.view.currentIndex === model.index } } }
-
I think I can explain it better with an example. There is "the_button" and if it gets pressed the second item of the list should be selected (set as the currentItem). Like "the_list_view.childAt(0,1).selected = true"?
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Layouts 1.12 import QtQuick.Controls 2.12 Window { visible: true width: 250 height: 350 title: qsTr("Hello World") Component { id: the_delegate Item { width: 180; height: 40 Column { Text { text: '<b>Name:</b> ' + name } Text { text: '<b>Number:</b> ' + number } } } } ColumnLayout { ListView { id: the_list_view implicitWidth: 250 implicitHeight: 250 anchors.fill: parent clip: true highlight: Rectangle { color: "lightsteelblue"; radius: 5 } focus: true delegate: the_delegate model: ListModel { id: the_model ListElement { name: "Bill Smith" number: "555 3264" } ListElement { name: "John Brown" number: "555 8426" } ListElement { name: "Sam Wise" number: "555 0473" } } } Button { id: the_button implicitWidth: 200 implicitHeight: 50 text: "the button" onPressed: //how to activate (simulate a click on) the second ListElement "John Brown" by its index. //Like: "the_list_view.childAt(0,1).selected = true" } } }
-
Set
highlightFollowsCurrentItem: true
property of ListView, then change its current index. -
Thanks to both of you. As Mammamia write a list item can be selected by setting the currentIndex. But this does not simulate a mouse click. Anyway with currentIndex I can set the currentItem and from there I can call a function of the_delegate which does the rest.
Next time I will describe my problem better. I thought a selection of an item will trigger a onClicked event automatically.
Thanks again, here is my final solution:
Component { id: the_delegate ... function simulateSomething() {...} } ListView { id: the_list_view ... function simulateSomethingOnItem(index) { currentIndex = index; currentItem.simulateSomething(); } } Button { ... onClicked: the_list_view.simulateSomethingOnItem(1) }
-
ListView destroys delegates that comes out of its view port, so this can be impossible in some ways.