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 { Q_GADGET public: enum class CarType { NO_CAR = 0, SLOW_CAR, FAST_CAR, HYPER_CAR }; 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;} public: CarType m_carType; int m_speed; }; Q_DECLARE_METATYPE(Player) #endif
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: " << mp.name(); //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); qRegisterMetaType<Player>(); //Create a player and set the speed Player p1; p1.setSpeed(30); const QMetaObject *mo = &p1.staticMetaObject; qInfo() << "Player speed before gadgetExplorer: " << p1.getSpeed(); gadgetExplorer(mo); qInfo() << "Player speed after gadgetExplorer: " << p1.getSpeed(); return a.exec(); }
Thanks for your time.
-
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. -
@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:
- https://doc.qt.io/qt-5/qobject.html#staticMetaObject-var (this is written for QObjects but it also applies to QGadgets)
- https://doc.qt.io/qt-5/qobject.html#Q_GADGET