How to do a “is_a”, “typeof” or instanceof in QML?

后端 未结 4 1888
南旧
南旧 2020-12-23 21:00

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.childr         


        
4条回答
  •  无人及你
    2020-12-23 22:02

    Since Qt 5.10, you can finally use instanceOf to check whether a variable is of a certain QML type, see "QML Support for Enum and InstanceOf Type Checks".

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

提交回复
热议问题