如何访问Repeater类型内部的子项、Row等布局类型内部的子项以及ListView内部的子项等。。。
1、测试代码
import QtQuick 2.0
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQml 2.12
Window {
id: window
objectName: "myWindow"
visible: true
width: 600
height: 250
title: qsTr("Hello World")
Column {
spacing: 10
// 1、Repeater中项的获取(通过itemAt()方法)
Row {
spacing: 10
Repeater {
id: rept
model: 3
Button {
text: "button" + index
background: Rectangle {
color: "green"
MouseArea {
anchors.fill: parent
onClicked: {
console.log(index)
}
}
}
}
}
Component.onCompleted: {
for (var item = 0; item < rept.count; item++) {
console.log(rept.itemAt(item).text)
}
}
}
// 2、Row等布局中子项的获取(Item的children属性)
Row {
id: row
spacing: 10
Button {
text: "click"
}
Text {
text: "HelloWorld"
}
Rectangle {
width: 100
height: 50
color: "red"
}
}
Button {
text: "获取Row布局中的子项"
onClicked: {
for (var i = 0; i < row.children.length; i++) {
//console.log("===> " + row.children[i])
if (row.children[i] instanceof Button) {
console.log(row.children[i].text)
}
}
}
}
// 3、获取ListView中的子项(ListView的contentItem属性)
Row {
ListView {
id: listView
width: 100
height: 50
model: ["AAA", "BBB", "CCC"]
delegate: Text {
text: index + " " + modelData
}
}
}
Button {
text: "获取ListView中的子项"
onClicked: {
for (var i = 0; i < listView.contentItem.children.length; i++) {
//console.log(listView.contentItem.children[i])
if (listView.contentItem.children[i] instanceof Text) {
console.log(listView.contentItem.children[i].text)
}
}
}
}
}
}
2、效果演示
3、其他
关于JavaScript中的 instanceof
运算符的使用,参考 JavaScript变量、数据类型、运算符 一文。