3

I have a QVariantMap with data. Inside the QVariant I can store custom class declared and registered in meta-system.

I know does exists QVariant::value<XXX>() but since i don't know a-priori what XXX is I cannot do that.

So I tried to convert to QObject* both with QVariant::value<QObject*> and qvariant_cast but it seems to hold a void pointer:

My attempt:

MyClass* obj = new MyClass();
QVariant variant = QVariant::fromValue<MyClass*>(obj);  // it works;

qDebug() << variant; // Qvariant(MyClass*,)

QObject* obj2 = variant.value<QObject*>();

qDebug() << obj2; // QObject(0x0)
Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
Moia
  • 2,216
  • 1
  • 12
  • 34
  • MyClass inherits from QObject? – eyllanesc Aug 08 '18 at 16:05
  • @eyllanesc it does – Moia Aug 08 '18 at 16:06
  • 1
    I just tried it in Qt 5.11.2 and it works properly: `QVariant(QObject*, QObject(0x55c48a9bfd50)) QObject(0x55c48a9bfd50)`, I could provide a [mcve], I do not need to use https://stackoverflow.com/a/44503822/8805095 – eyllanesc Aug 08 '18 at 16:10
  • Possible duplicate of [QVariant with custom class pointer does not return same address](https://stackoverflow.com/questions/44501171/qvariant-with-custom-class-pointer-does-not-return-same-address) – eyllanesc Aug 08 '18 at 18:38

1 Answers1

3

The OP mentions it works with:

QVariant variant(QVariant::fromValue(static_cast<void*>(obj)));
auto test = static_cast<QObject*>(variant.value<void*>());

qDebug() << obj2; // MyClass(0x8a99838

As specified in this answer

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55