我有一个“顶级” Q_GADGET
,在这个里面Q_GADGET
,我有一个指向另一个的指针Q_GADGET
。我正在尝试使用函数 readOnGadget 来显示两个对象存储的值。我可以在顶层做到这一点Q_GADGET
,但是从内部读取的值Q_GADGET
是错误的。这是我的代码:
Q_小工具:
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <QObject>
//Nested Q_GADGET
struct P2D {
Q_GADGET
Q_PROPERTY(P2D p2d READ getP2D )
Q_PROPERTY(float m_x READ getX WRITE setX)
Q_PROPERTY(float m_y READ getY WRITE setY)
public:
float m_x;
float m_y;
P2D getP2D() {return *this;}
float getX() {return this->m_x;}
void setX(float x) {this->m_x = x;}
float getY() {return this->m_y;}
void setY(float y) {this->m_y = y;}
}; Q_DECLARE_METATYPE(P2D)
//Main Q_GADGET
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)
Q_PROPERTY(P2D* p2d READ getP2D )
Player getPlayer() { return *this;}
int getSpeed() {return this->m_speed;}
void setSpeed(int speed) {this->m_speed = speed;}
CarType getCarType() { return m_carType;}
P2D* getP2D() {return this->p2d;}
public:
CarType m_carType;
int m_speed;
P2D *p2d;
}; Q_DECLARE_METATYPE(Player)
#endif
主要的:
#include <QCoreApplication>
#include <iostream>
#include <QMetaObject>
#include "example.h"
#include <QDebug>
#include <QMetaProperty>
#include <QPointer>
void* pointer = nullptr;
void gadgetExplorer(void *ptr, const char* s)
{
//Receives pointer and access its meta-object
qInfo() << "Pointer received is: " << ptr;
int typeId = QMetaType::type(s);
const QMetaObject *mo = QMetaType::metaObjectForType(typeId);
//Prints class name
qInfo() << "Q_GADGET: " << mo->className();
//Iterates through properties
QMetaProperty mp;
for(int i = 1; i < mo->propertyCount(); i++)
{
mp = mo->property(i);
qInfo() << "Q_PROPERTY: " << mp.name() << "Value: " << mp.readOnGadget(ptr);
//1024 = user defined, so it's another gadget (P2D)
if(int(mp.type()) == 1024)
gadgetExplorer(pointer, mp.typeName());
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qRegisterMetaType<Player>();
qRegisterMetaType<P2D>();
qRegisterMetaType<P2D*>();
Player p1;
p1.setSpeed(30);
p1.p2d = new P2D();
p1.p2d->setX(10.0);
p1.p2d->setY(25.0);
qInfo() << "Pointer to inner Q_GADGET: " << &p1.p2d;
pointer = &p1.p2d;
gadgetExplorer(&p1, "Player");
qInfo() << "Value of m_x outside funtion :" << p1.p2d->getX();
return a.exec();
}
我从代码中得到的输出是:
Pointer to inner Q_GADGET: 0x7ffdb82e3418
Pointer received is: 0x7ffdb82e3410
Q_GADGET: Player
Q_PROPERTY: m_speed Value: QVariant(int, 30)
Q_PROPERTY: m_carType Value: QVariant(int, -1204931552)
Q_PROPERTY: p2d Value: QVariant(P2D*, )
Pointer received is: 0x7ffdb82e3418
Q_GADGET: P2D
Q_PROPERTY: m_x Value: QVariant(float, 2.85026e+31)
Q_PROPERTY: m_y Value: QVariant(float, 3.09603e-41)
Value of m_x outside funtion : 10
我期望 m_x 和 m_y 的值分别为 10 和 25。我传递给的指针readOnGadget
似乎是正确的。全局指针仅用于示例。我究竟做错了什么?