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

Scott Montgomerie picture Scott Montgomerie · Dec 18, 2012 · Viewed 16k times · Source

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

How does one accomplish this?

Answer

user5315753 picture user5315753 · Jan 26, 2018

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