Nominate our 2022 Qt Champions!

Is it possible to read a Q_PROPERTY with a QMetaObject pointer only?

  • Hello everyone. I'm tinkering a bit with QMetaObjects as of late, and I know you can read their properties using QMetaObjects readOnGadget(const void* gadget). However, let's assume I do not have a pointer to the gadget, I only have a QMetaObject of the gadget. Is there a way to do it? Here's my snippet of code:

    Q_GADGET that makes the QMetaObject:

    #ifndef EXAMPLE_H
    #define EXAMPLE_H
    #include <QObject>
    struct Player {
        enum class CarType {
            NO_CAR = 0,
        }; Q_ENUM(CarType)
        Q_PROPERTY(Player player READ getPlayer)
        Q_PROPERTY(int m_speed READ getSpeed WRITE setSpeed)
        Q_PROPERTY(CarType m_carType READ getCarType)
        Player getPlayer() { return *this;}
        int getSpeed() {return this->m_speed;}
        void setSpeed(int speed) {this->m_speed = speed;}
        CarType getCarType() { return m_carType;}
        CarType m_carType;
        int m_speed;

    My main:

    #include <QCoreApplication>
    #include <iostream>
    #include <QMetaObject>
    #include "example.h"
    #include <QDebug>
    #include <QMetaProperty>
    void gadgetExplorer(const QMetaObject *mo)
        qInfo() << "Q_GADGET: " << mo->className();
        QMetaProperty mp = mo->property(1);
        qInfo() << "Q_PROPERTY: " <<;
        //Read player's speed
        //Is it possible to do it just with the meta object?
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        //Create a player and set the speed
        Player p1;
        const QMetaObject *mo = &p1.staticMetaObject;
        qInfo() << "Player speed before gadgetExplorer: " << p1.getSpeed();
        qInfo() << "Player speed after gadgetExplorer: " << p1.getSpeed();
        return a.exec();

    Thanks for your time.

  • Moderators

    Think about it, read a property of what? The data is in the object, the QMetaObject just facilitates the reflection capabilities for the class, so without an object there's nothing to read.

  • Moderators

    @raphasauer said in Is it possible to read a Q_PROPERTY with a QMetaObject pointer only?:

    I only have a QMetaObject of the gadget.

    To add to @kshegunov's post: All instances of your QGadget share the same QMetaObject. You can check this yourself:

    Player p1;
    Player p2;
    qDebug() << "Are they the same?" << (&p1.staticMetaObject == &p2.staticMetaObject)

    See also:

Log in to reply