qtqml

How to get the typename of a QObject instance parsing QML?


I have got a QQuickView which has loaded a qml file like the following.

Rectangle { width: 100; height: 100 }

Then I am retrieving the root object via QObject *root = view->rootObject(). Now I want to get the class name from this object. The following code results into "QQuickRectangle"

root->metaObject()->className()

But what I want is "Rectangle" just like the typename in the qml file. Any idea?

Edit: I want to build a treeview with the object hirarchie of a qml file like QtCreator.

enter image description here


Solution

  • There is a pattern there, for qml types implemented in C++ the name would be QQuickSomething, for qml types implemented in qml the name would be Something_QMLTYPE_X_MAYBEMORESTUFF(objAddress).

    So you can do some basic string editing depending on the result you get to isolate the actual type name:

    QString name = QString(root->metaObject()->className());
    if (name.contains("QQuick")) name.remove("QQuick");
    else if (name.contains("QMLTYPE")) name.remove(QRegExp("_QMLTYPE_[0-9]*.*"));
    // else it might be just a QObject or your on custom type you should handle
    

    Edit: I want to build a treeview with the object hirarchie of a qml file like QtCreator.

    Unless you are willing to dig into and use private APIs, it would likely be easier and also more useful to have your own custom model to drive both a view and the actual object tree. Also, QML is quite easy to parse, I'd personally buckle down and write a parses faster than it would take me to get into the existing one, especially if all that is needed is an object tree outline, but YMMV.