问题描述
我想运行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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!