PDA

View Full Version : QSharedPointer in a QVariant and back again



tomschuring
24th January 2012, 05:14
I'm trying to store QSharedPointer<MyClass> values in a QVariant (so i can store it as custom data in a QComboBox) using:


MyClass* myIns = new MyClass();
QSharedPointer<MyClass> asp(myIns);
QVariant aVariant = QVariant::fromValue(asp);

how do i retrieve the QSharedPointer<MyClass> back from aVariant ?

i tried:


QSharedPointer<MyClass> retValue = v.value<QSharedPointer<MyClass> >();

but the compiler doesn't like that.
note: MyClass is derived of QObject

ChrisW67
24th January 2012, 05:53
You do it the way you have tried. This works for example:


#include <QtCore>
#include <QDebug>

class MyClass: public QObject {
Q_OBJECT
public:
MyClass(QObject *p = 0): QObject(p) { }
};

Q_DECLARE_METATYPE( QSharedPointer<MyClass> )


int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

QSharedPointer<MyClass> in( new MyClass );
QVariant v = QVariant::fromValue( in );

QSharedPointer<MyClass> out = v.value<QSharedPointer<MyClass> >();
qDebug() << in << out << (in == out);

return 0;
}
#include "main.moc"

tomschuring
24th January 2012, 23:02
thanks Chris !!
that did the job.

i missed the Q_DECLARE_METATYPE macro.
just looking in the headers what the macro does.

not quite sure but it looks like it registers the class with the constructor and destructor, but it seems a bit over my head.
can easily remember to call the macro whenever i use QVariant for my own class through.


thanks again,
tom