設定
我有ListView一些通用模型和myDelegate組件。
ListView {
id: myListView
delegate: myDelegate
...
}
在myDelegate組件中,我想設定ListView's currentItem。我目前這樣做:
Component {
id: myDelegate
...
MouseArea {
onClicked: myListView.currentIndex = model.index
}
}
一切都按預期作業。
問題
眾所周知,在委托中使用ListView's是不好的做法id,因為可能有多個 ListView 使用相同的委托組件。因此,應改用ListView.view附加屬性。
但是,如果我像這樣更改委托的代碼:
Component {
id: myDelegate
...
MouseArea {
onClicked: ListView.view.currentIndex = model.index
}
}
我得到一個TypeError: Value is null and could not be converted to an object.
使用以下 console.logs,我發現它ListView.view始終為 null。我不明白為什么。設定currentIndex上ListView本身也失敗。
onClicked: {
console.log("ListView:", ListView)
console.log("ListView.view:", ListView.view)
console.log("ListView.currentIndex:", ListView.currentIndex)
}
...
qml: ListView: QQuickListViewAttached(0x6db0b30)
qml: ListView.view: null
qml: ListView.currentIndex: undefined
最小的可重復示例
Qt
Creator
main.qml 中的Qt v6.2.1 Empty Qt Quick 專案:
import QtQuick
import QtQuick.Window
Window {
width: 150
height: 350
visible: true
Component {
id: myDelegate
Rectangle {
color: ListView.isCurrentItem ? "pink" : "lightblue"
implicitWidth: 150
implicitHeight: 50
MouseArea {
anchors.fill: parent
onClicked: {
ListView.view.currentIndex = model.index
console.log("ListView", ListView)
console.log("ListView.view", ListView.view)
}
}
Text {
anchors.centerIn: parent
text: model.index
}
}
}
ListView {
id: myListView
anchors.fill: parent
spacing: 2
model: 6
delegate: myDelegate
}
}
uj5u.com熱心網友回復:
附加屬性設定在委托的根中,因此如果您想從子項訪問,則必須使用根作為參考:
Component {
id: myDelegate
Rectangle {
id: root_delegate // <---
color: ListView.isCurrentItem ? "pink" : "lightblue"
implicitWidth: 150
implicitHeight: 50
MouseArea {
anchors.fill: parent
onClicked: {
root_delegate.ListView.view.currentIndex = model.index;
console.log("ListView", root_delegate.ListView);
console.log("ListView.view", root_delegate.ListView.view);
}
}
Text {
anchors.centerIn: parent
text: model.index
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349133.html
上一篇:如何根據空行/空白行拆分字串?
