Reputation: 11732
Consider a QML type (defined in QML, not in C++):
Foo {
}
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.
Upvotes: 2
Views: 1015
Reputation: 101
IMO you are part of the way there. Your best bet is using a combination of QQuickItem::inherits
and QMetaObject::className
.
This way you can figure out if it is actually a Foo
or derived from Foo
.
const QByteArray foo = QByteArrayLiteral("Foo");
if (item->metaObject()->className() == foo || item->inherits(foo)) {
// It's a Foo
}
Upvotes: 0
Reputation: 49319
You could use a magic key property:
Foo {
property bool isFoo : true
}
And then from C++:
if (obj->property("isFoo").toBool())
If the object doesn't have that property, then the condition should fail. This will also work for "derived" objects as the property will be "inherited", for example if something extends Foo
but is not necessarily named FooSomething
but rather SomethingFoo
.
Naturally, there will be some overhead, which could get pronounced in scenarios where you need a lot of type checks on many instances. What I tend to do is have a single quint32 type
property implemented efficiently on C++ level, then from QML this is explicitly set in objects where type information is necessary. This way the overhead is minimized, and it is also faster to access than using property(name)
.
Upvotes: 3