Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

How does one accomplish this?

like image 541
Scott Montgomerie Avatar asked Dec 17 '12 23:12

Scott Montgomerie


2 Answers

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))
  }
}
like image 131
user5315753 Avatar answered Oct 25 '22 20:10

user5315753


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")
        }
    }
  }
}
like image 21
JuliusG Avatar answered Oct 25 '22 18:10

JuliusG