Search code examples
qtqmlqt5

How to print a list of custom properties of a QML object?


Having created a QML QtObject:

QtObject {
    property int p: 42
    property int q: 44
}

After storing it in a local variable QObject *obj, how to print all custom property names and possibly values (i.e. only p and q for the example above)? I'd like this to work for any class (not just QtObject) and not print properties that were already declared with Q_PROPERTY.

Clarification: by "custom" I do not mean properties added through QObject::setProperty that were not declared using Q_PROPERTY. I mean properties declared in QML through property <type> <name>: <value> notation that were not declared using Q_PROPERTY in QObject subclass for that QML object. Quick test shows that those properties do not come up in QObject::dynamicPropertyNames.


Solution

  • All information about properties, invokable methods (slots too) and signals are stored by QMetaObject in every QObject. If you want to list all properties in an object:

    QObject *obj = findObjectMethod();
    QMetaObject *meta = obj->metaObject();
    int n = meta->propertyCount();
    for(int i = 0; i < n; ++i)
    {
      qDebug() << "Property: " << meta->property(i)->name();
    }