如何在QML中执行"is_a","typeof"或instanceof?

Sco*_*rie 26 javascript qml

我想运行QML组件列表并选择一种类型:

for (var i = 0; i < controls.children.length; ++i) {
     if ( typeof (controls.children[i].height) == "QDeclarativeRectangle")
     {
        // do stuff
     }
}
Run Code Online (Sandbox Code Playgroud)

如何实现这一目标?

Jul*_*usG 19

你不能直接使用typeof,因为它总是会将你的'object'作为任何QML元素的类型返回.但是你可以使用几种替代方案.一种是将每个元素的objectName设置为其类型,并在循环中检查它或定义属性并检查该属性.这将需要更多的工作,但您可以创建具有此属性的qml元素,而不是在需要的地方使用它.这是一个示例代码:

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")
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 12

从Qt 5.10开始,您最终可以使用instanceOf来检查变量是否属于某种QML类型:https://v-play.net/updates/v-play-2-15-0-qt-5-10-qt -creator-4-5-支撑火力数据结构和-查询#QT-5-10-QML-枚举的instanceof

import VPlayApps 1.0
import QtQuick 2.0

App {
  // two QML items, used for type checking
  Item { id: testItem }
  Rectangle { id: testRect }

  // function to check wheter an item is a Rectangle
  function isRectangle(item) {
    return item instanceof Rectangle
  }

  // type check example
  Component.onCompleted: {
    console.log("testItem is Rectangle? "+isRectangle(testItem))
    console.log("testRect is Rectangle? "+isRectangle(testRect))
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用 Qt 5.14,这似乎不起作用。我想在实体中找到`Transform`组件,所以我有一个类似`for(var i = 0; i &lt;entity.components.length; i++) { console.log("component", i, ": ",entity.components[i], "instance of Transform?",entity.components[i] instanceof Transform) }` 但它打印: *component 2 : Qt3DCore::QTransform(0x7fd85a4279b0) instance of Transform? 错误的* (2认同)

jic*_*chi 11

这是使用toString()的另一种方法(可能无法移植到未来版本的QML):

function qmltypeof(obj, className) { // QtObject, string -> bool
  // className plus "(" is the class instance without modification
  // className plus "_QML" is the class instance with user-defined properties
  var str = obj.toString();
  return str.indexOf(className + "(") == 0 || str.indexOf(className + "_QML") == 0;
}

...

for (var i = 0; i < controls.children.length; ++i) {
   if (qmltypeof(controls.children[i].height, "QDeclarativeRectangle"))
   {
     // do stuff
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 不错的把戏。为方便起见,我会修改 return 语句:`return str.indexOf(className + "(") == 0 || str.indexOf(className + "_QML") == 0 || qmltypeof(obj, "QQuick" + className );` (2认同)
  • 即使它不可移植,`toString` 也非常适合调试。 (2认同)