Thursday, November 18, 2010

Storing custom class in QVariant

One of my friend asked me, how we can store custom class or structure in QVariant.

I gave him following sample.Posting same sample in hope it will help others as well.

#include <QCoreApplication>
#include <QPoint>
#include <QVariant>

class MyStruct
{
public:
    QString name;
    QString id;
    QPoint point;
};
Q_DECLARE_METATYPE(MyStruct)

int main(int argc, char *argv[])
{    
    qRegisterMetaType<MyStruct>("MyStruct");

    MyStruct test1;
    test1.name="test";
    test1.id = "testid";
    test1.point=QPoint(100,100);
    QVariant v;
    v.setValue<MyStruct>(test1);

    MyStruct test2 =v.value<MyStructl>();

}

If you need to serialize this variant than you will need to provide serialization method for custom class and also need to register them with metatype system using qRegisterMetaTypeStreamOperators.

No comments:

Post a Comment