问题描述
我想遍历 QML 组件列表并选择一种类型:
I want to run through a list of QML components and choose one type:
for (var i = 0; i < controls.children.length; ++i) {
if ( typeof (controls.children[i].height) == "QDeclarativeRectangle")
{
// do stuff
}
}
如何做到这一点?
推荐答案
你不能直接使用 typeof 因为它总是会返回你 'object' 作为任何 QML 元素的类型.但是,您可以使用多种替代方法.一种是将每个元素的 objectName 设置为其类型并在循环中检查它或定义一个属性并检查该属性.这将需要更多的工作,但您可以创建具有此属性的 qml 元素,而不是在需要的任何地方使用它.这是一个示例代码:
You can't use typeof for this directly because it will always return you 'object' as a type of any QML element. There are several alternatives however that you could use. One is setting the objectName of the each element to its type and check that in your loop or define a property and check for that property. This will require a bit more work but you could create your qml element that has this property and than use it wherever you need it.Here is a sample code:
Rectangle {
id: main
width: 300; height: 400
Rectangle {
id: testRect
objectName: "rect"
property int typeId: 1
}
Item {
id: testItem
objectName: "other"
}
Component.onCompleted: {
for(var i = 0; i < main.children.length; ++i)
{
if(main.children[i].objectName === "rect")
{
console.log("got one rect")
}
else
{
console.log("non rect")
}
}
for(i = 0; i < main.children.length; ++i)
{
if(main.children[i].typeId === 1)
{
console.log("got one rect")
}
else
{
console.log("non rect")
}
}
}
}
这篇关于如何做一个“is_a"、“typeof"还是 QML 中的 instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!