How to do a quot;is_aquot;, quot;typeofquot; or instanceof in QML?(如何做一个“is_a、“typeof还是 QML 中的 instanceof?)
问题描述
我想遍历 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何做一个“is_a"、“typeof"还是 QML 中的 instanceof?
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
