How to check from C++ whether an object is of QML type Foo



  • Consider a QML type Foo (defined in QML, not in C++):

    // in Foo.qml
    Item {
        // ...
    }
    

    And assume I have a QQuickItem* item variable in C++. How do I check if the variable is of type Foo?

    If Foo was a C++ type, I could do this:

    qobject_cast<Foo*>(item) == nullptr
    

    Since Foo is a QML type, one option would be

    item->metaObject()->className().beginsWith("Foo")
    

    (className() returns something like Foo_QMLTYPE_0)

    But that seems unreliable and hacky.



  • @Stefan-Monov76

    Isn't it work the same?
    If you have and item for requesting metaObject(), you still can use qobject_cast()



  • @Roumed: I can't use qobject_cast, because Foo is not a C++ class (it's a QML type). I can't pass it as a template parameter to qobject_cast.



  • @Stefan-Monov76
    Every QML type is a C++ type, registred for QML.
    For example WebViewLoadRequestin in QML is QQuickWebViewLoadRequest in C++.

    So since your item has metaObject() it has to be QObject derived.
    The only question is which type is it.


  • Lifetime Qt Champion

    Hi,

    Out of curiosity, why do you need that ?



  • @Roumed: Not every QML type is a C++ type registered for QML. Types defined in QML are not C++ types. I think I see where the confusion comes from. I had written the example QML type declaration Foo { } in my original post, but what I actually meant was a file called Foo.qml containing an Item as the root object. Edited.

    @SGaist: I'm iterating over the children of a QML item Container and using them as texture sources for custom OpenGL rendering. But I want to fetch just those children that I have coded, not the ones that Qt adds silently. E.g. if I put the Container in a layout, then Qt inserts something like a QQuickLayoutAttached object as a child of the Container.



  • @Stefan-Monov76 , I see you, agree.
    If understand you right about your task about OpenGL rendering, you need only visual items.
    So, how about iterate not over children but over childItems?

    And about checking qml types: I think checking meta object name is the only way.



  • @Roumed: Thanks, the childItems suggestion sounds good, I'll implement it as it's more semantically correct. But for now I'll combine it with the isFoo workaround described here, because I'm not sure if Qt won't decide to insert visual children in my item if I change something in the future. Just like I didn't expect it would insert nonvisual children.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.