当我试图让孩子ID轻微修改此http://qmlbook.github.io/en/ch01/index.html示例
时// animate.qml
import QtQuick 2.0
Item
{
id: root
width: background.width
height: background.height
property string information: "this is root"
property int rotationStep: 45
Image {
id: background
source: "images/background.png"
}
Image {
id: pole
property string information: "this is pole"
x: (root.width - width)/2+2
y: root.height - height
source: "images/pole.png"
}
Image {
id: pinwheel
anchors.centerIn: parent
source: "images/pinwheel.png"
property string information: "this is pinweel"
// visible: false
Behavior on rotation {
NumberAnimation { duration: 125 }
}
}
Image {
id: blur
opacity: 0
anchors.centerIn: parent
source: "images/blur.png"
property string information: "this is blur"
// visible: false
Behavior on rotation {
NumberAnimation { duration: 125 }
}
Behavior on opacity {
NumberAnimation { duration: 125 }
}
}
// M1>>
focus: true
Keys.onLeftPressed: {
blur.opacity = 0.8
pinwheel.rotation -= root.rotationStep
blur.rotation -= root.rotationStep
}
Keys.onRightPressed: {
blur.opacity = 0.5
pinwheel.rotation += root.rotationStep
blur.rotation += root.rotationStep
}
Keys.onReleased: {
blur.opacity = 0
}
Keys.onSpacePressed:
{
for (var i=0; i<root.children.length; ++i)
console.info(root.children[i].information)
}
Keys.onDeletePressed:
{
for (var i=0; i<root.children.length; ++i)
console.info(root.children[i].id)
}
// <<M1
}
不幸的是,按Delete键会给我一个错误:
qml: undefined
qml: undefined
qml: undefined
qml: undefined
而不是按空格键:
qml: undefined
qml: this is pole
qml: this is pinweel
qml: this is blur
为什么此脚本会返回未定义的ID?
我需要遍历一些对象并能够告诉它是什么 - 所以我需要知道如何遍历根树以获取其子节点及其对象类型的id。
不幸的是我无法打印最常见的id并且不得不添加一些简单的属性来完成它但这意味着在现实生活中需要很多工作,因为每个对象都需要信息属性:(
重申:
答案 0 :(得分:1)
Id不是普通的对象属性,因此当您尝试通过js进行评估时,它是未定义的。并且qml不提供typeof
等运营商。因此,您需要手动添加type
或objectname
属性。我会考虑继承Image
并添加type
。参考:How to do a "is_a", "typeof" or instanceof in QML?
Item
{
id: root
Image {
id: background
type: "image"
}
Image {
id: pole
type: "image"
}
function iter(){
for(var i = 0; i < root.children.length; ++i)
if(root.children[i].type==="image"){
//balabala
}
}
}
}