I have a QML ListView
where the delegate loads it's component from another file. When clicking on an delegate item, I want to update ListView
. CurrentIndex
and highlight
the selected item.
It works, when I explicitly set the id
of the ListView
. However since I want to use the delegate's Component
also for other ListView
s, I'm stuggeling to find a generic way how to access ListView.currentIndex
from within a delegate Component
.
Here is the Code:
main.qml
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
ListModel {
id: contactsModel
ListElement {
name: "Bill Smith"
}
ListElement {
name: "John Brown"
}
ListElement {
name: "Sam Wise"
}
}
ListView{
id: contactsView
anchors.left: parent.left
anchors.top: parent.top
width: parent.width
height: parent.height
orientation: Qt.Vertical
spacing: 10
model: contactsModel
delegate: Contact{}
}
}
Contact.qml (Component used by delegate)
import QtQuick 2.0
Component{
id: contact
Rectangle{
width: 200
height: 50
color: ListView.isCurrentItem ? "#003366" : "#585858"
border.color: "gray"
border.width: 1
MouseArea{
anchors.fill: parent
onClicked: {
ListView.currentIndex = index; // <---- does not work
// contactsView.currentIndex = index; // <---- Works
}
}
Text{
anchors.centerIn: parent
color: "white"
text: name
}
}
}
Any help is really appreciated!