2023-06-09 QML获取一个属性的类型

7 篇文章 0 订阅

前言

在qml编程中,某些情况可能会需要知道一个属性的类型,
比如下代码

var component = Qt.createComponent(baseItem.visualQML)
if(component.status === Component.Error){
console.log("Error Loading:",baseItem.visualQML,component.errorString())
return
 }
var _visualItem = component.createObject(control,{visualItem : object})

// 添加到地图上,需要判断是Item还是ItemGroup
// ItemGroup的父节点是MapQuickItem,instanceof 可能会识别到MapQuickItem,但实测后发现不会
if(_visualItem instanceof MapItemGroup)
	map.addMapItemGroup(_visualItem)
else if(_visualItem instanceof MapQuickItem)
    map.addMapItem(_visualItem)

这样创建出的组件,不同组件会有不用应用方式,在使用之前就必须要判断它的类型,上述代码使用了 instanceof 来判断类型。

一、instanceof

它是js里的关键字:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
现在在QML中也会支持。
经测试,instanceof 只会判断出最近一层的类型,比如Rectangle是基于Item实现的,但下代码只能判断出Rectangle

// file Rect.qml
Rectangle{
//.............
}
var component = Qt.createComponent("Rect.qml")
var _visualItem = component.createObject()

(_visualItem instanceof Rectangle)   // true
(_visualItem instanceof Item)  //false

二、使用 objectName

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")
        }
    }
  }
}

些方式是将自己组的组件填写上 objectName属性,创建组件后也可判断

来源:https://stackoverflow.com/questions/13923794/how-to-do-a-is-a-typeof-or-instanceof-in-qml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值