Perhaps the title looks somewhat unclear, so I’ll go straight to the example:
double d = 3.14; QVariant v(d); qDebug() << v.value<int>(); //3 QVariant performed a cast of double -> int .
I want to do the same thing, but with pointers:
class Foo : public QObject{ Q_OBJECT; }; Q_DECLARE_METATYPE(Foo*) static const int __idFoo = qRgisterMetaType<Foo*>("Foo*"); //... Foo *foo = new Foo(); QVariant v = QVariant::fromValue(foo); qDebug() << v.value<QObject*>(); //QObject(0x0) Type cast did not happen.
Question: Is it possible in some way to place a pointer to an object of a derived class in QVariant , but to extract a pointer to an object of a base class?
UPD: The code is almost the same as mine:
class IRow : public QObject{ //... }; class FirstRow : public IRow{ //... }; class SecondRow : public IRow{ FirstRow *_first Q_PROPERTY(FirstRow* first READ first WRITE setFirst) public: FirstRow* first() const{ return _first; } void first(FirstRow *first){ _first = first; } //... }; Somewhere else there is a function that knows nothing about specific implementations of the IRow interface. It should read all available properties, of the object that came to it in the form of QVariant (otherwise, there is work with models), and bring the resulting value to the interface type ( IRow ). And here it is not given. In Qt5, it should, but in Qt4 - no way. If you use the @ixSci solution, then the SecondRow class will look like:
class SecondRow : public IRow{ FirstRow *_first Q_PROPERTY(FirstRow* first READ _first WRITE _setFirst) public: FirstRow* first() const{ return _first; } void first(FirstRow *first){ _first = first; } private: IRow* _first() const{ return first(); } void _setFirst(IRow *first){ _setFirst(qobject_cast<FirstRow*>(first)); } //... }; It works, but the number of setters and getters has doubled.
Q_DECLAREandqRegistershould not be needed in this case. For the rest, it is strange that it does not work. I do not have 4.8 to check, but in version 5 everything works as it should. - ixSci 1:08value? - αλεχολυτv.value<void*>()returns0. If you writev.value<Foo*>(), then that pointer that I placed there will return. - yrHeTaTeJlbvalueknows nothing about specific classes. He knows only the base class (interface). And I can’t get the content ofvaluein any way, if I don’t know the real type of this content - yrHeTaTeJlb