Please nominate your Qt Champions for 2021!

Reflection on Qt

  • Hi everybody, I would use Reflection on Qt, but I do not know how I can do that. In Java, any object can be instantiated and be called even if unknown. In Qt, I can only do this when I know that this object. Has anyone used Reflection in Qt?

    In my Object:

    class Obj : public QObject

    Q_INVOKABLE Obj(QObject *parent = 0);
    Q_INVOKABLE virtual ~Obj();

    Q_INVOKABLE virtual QVariant execute (QList<QVariant> &);
    Q_INVOKABLE uint getKey();


  • I don't know much about Java or its reflection features. Does QMetaObject provide what you need?

  • Reflection itself does not exist in C++ (see wikipedia: ).
    To use the meta data system, you can achive something like that, but not for constructors (which you seem to think in the above code snippet).

  • Actually, Q_INVOKABLE is possible on constructors, and if you have such a constructor, you can use QMetaObject::newInstance to create an object of the requested type. But I am not sure that is what tchoninho is after?

  • Well, you could do some nasty thing like this:

    @typedef QVariant (Obj::*pt2Member)(QList<QVariant> &);
    QMap<QString, pt2Member> functions;
    QVariant result = functions["execute"](QList<QVariant> &);

    Use this if there is no other option :)
    (You will still need a this reference I think, haven't tried this out!)

Log in to reply