【QML】ListView 报错 ReferenceError: index is not defined
问题
使用ListView的过程中报错:ReferenceError: index is not defined
错误代码
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Rectangle {
width: 120
height: 300
color: "white"
ListView {
id: view
anchors.fill: parent
anchors.margins: 20
clip: true
model: ListModel{
ListElement{name: "admin"}
ListElement{name: "jack"}
ListElement{name: "tom"}
}
delegate: numberDelegate
spacing: 5
focus: true
}
Component {
id: numberDelegate
Rectangle {
required property string name //这里出的问题
width: ListView.view.width
height: 40
color: ListView.isCurrentItem?"gray":"lightGray"
Text {
anchors.centerIn: parent
font.pixelSize: 10
text: index
}
MouseArea{
anchors.fill: parent
onClicked:{
view.currentIndex = index //item切换
console.log("index"+index)
}
}
}
}
}
}
解决方法
- 方法1:
注释掉required property string name
这一行后,问题解决。
Component {
id: numberDelegate
Rectangle {
//required property string name //注释掉
width: ListView.view.width
height: 40
color: ListView.isCurrentItem?"gray":"lightGray"
Text {
anchors.centerIn: parent
font.pixelSize: 10
text: index
}
MouseArea{
anchors.fill: parent
onClicked:{
view.currentIndex = index //item切换
console.log("index"+index)
}
}
}
}
- 方法2:
添加required property int index
这一行代码
Component {
id: numberDelegate
Rectangle {
required property string name
required property int index //添加这一行
width: ListView.view.width
height: 40
color: ListView.isCurrentItem?"gray":"lightGray"
Text {
anchors.centerIn: parent
font.pixelSize: 10
text: index
}
MouseArea{
anchors.fill: parent
onClicked:{
view.currentIndex = index //item切换
console.log("index"+index)
}
}
}
}