如何访问Repeater类型内部的子项、Row等布局类型内部的子项以及ListView内部的子项等。。。

1、测试代码

import QtQuick 2.0import QtQuick.Controls 2.12import QtQuick.Window 2.12import QtQuick.Layouts 1.3import QtQml 2.12Window {id: windowobjectName: "myWindow"visible: truewidth: 600height: 250title: qsTr("Hello World")Column {spacing: 10// 1、Repeater中项的获取(通过itemAt()方法)Row {spacing: 10Repeater {id: reptmodel: 3Button {text: "button" + indexbackground: Rectangle {color: "green"MouseArea {anchors.fill: parentonClicked: {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: rowspacing: 10Button {text: "click"}Text {text: "HelloWorld"}Rectangle {width: 100height: 50color: "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: listViewwidth: 100height: 50model: ["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变量、数据类型、运算符 一文。