我有一个QMLListView
委托从另一个文件加载其组件的地方。单击委托项目时,我想更新ListView
. CurrentIndex
and highlight
所选项目。
当我明确设置时它有效id
of the ListView
。但是因为我想使用代表的Component
也为其他ListView
s,我正在努力寻找一种通用的方法来访问ListView.currentIndex
从代表内部Component
.
这是代码:
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{}
}
}
联系方式.qml(委托使用的组件)
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
}
}
}
非常感谢任何帮助!
这里有两个问题:
- 您需要符合资格
ListView
的附加属性以及从中访问它们的项目的名称。
- The
currentIndex
财产是的财产ListView物品种类 http://doc.qt.io/qt-5/qml-qtquick-listview.html#currentIndex-prop,不是附加属性对象 http://doc.qt.io/qt-5/qml-qtquick-listview.html#properties.
要解决这两个问题,请首先更改此设置:
ListView.currentIndex = index;
to this:
delegate.ListView.view.currentIndex = index;
然后给你的代表一个id
:
Component {
id: contact
Rectangle {
id: delegate
// ...
}
这(部分)由用法示例 http://doc.qt.io/qt-5/qml-qtquick-listview.html#example-usage文档部分:
ListView 将许多属性附加到委托的根项,例如 ListView:isCurrentItem。在以下示例中,根委托项可以直接作为 ListView.isCurrentItem 访问此附加属性,而子 contactInfo 对象必须以wrapper.ListView.isCurrentItem 形式引用此属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)