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 likeFoo_QMLTYPE_0
)But that seems unreliable and hacky.
-
Isn't it work the same?
If you have anditem
for requestingmetaObject()
, you still can useqobject_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
hasmetaObject()
it has to be QObject derived.
The only question is which type is it. -
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 calledFoo.qml
containing anItem
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 theContainer
in a layout, then Qt inserts something like aQQuickLayoutAttached
object as a child of theContainer
. -
@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 theisFoo
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.