I have two classes like this :
class Foo { public: Foo(int i) : _i(i) {} int _i; }; Q_DECLARE_METATYPE(Foo*)
class Bar : public Foo
{
public:
Bar(int i, int j) : Foo(i), _j(j) {}
int _j;
};
Q_DECLARE_METATYPE(Bar*)
My bench is like this :
int main(int argc, char *argv[]) { QApplication a(argc, argv); Bar* bar = new Bar(10,11); QVariant var = QVariant::fromValue(bar); Foo * foo = var.value<Foo*>(); // foo IS NULL QPushButton * b = new QPushButton(); QVariant v = QVariant::fromValue(b); QObject * object = v.value<QObject*>(); // object IS NOT NULL return a.exec(); }
Why is foo
null ?
QVariant
lets the polymorphism since I have no problem with object
Because
Foo
is not derived fromQObject
andQVariant
only supports polymorphism forQObject
-derived types.From the QVariant::value documentation:
(Emphasis mine). This is rehashed in the part about
QVariant::canConvert
that is referenced further down, and there is nothing else about pointer conversions.QVariant
simply does not support your scenario.The upside is that if you make
Foo
a subclass ofQObject
, you do not have to bother withQ_DECLARE_METATYPE
anymore.