Search code examples
qtqjsoncustom-data-type

How to register the following datatype to allow serialization?


I am using QJson to serialize a QObject-derived class. I am able to serialize the class itself without any problems, but when it comes to one of its members, I am having a bit of trouble.

The class is named CProject and it contains a property files which is defined as:

QList<CProjectFile> files;

When serializing an instance of CProject, I get a message in the console:

QMetaProperty::read: Unable to handle unregistered datatype 'QList<CProjectFile>' for property 'CProject::files'

I read somewhere that I have to register the datatype, so I added the following after the declaration of CProject:

Q_DECLARE_METATYPE(QList<CProjectFile>)

...and when that did nothing, I added:

qRegisterMetaType< QList<CProjectFile> >();

Nothing is working. What am I doing wrong?


Solution

  • I don't know how QJson works but perhaps it requires stream operators. Try as below after declaration of CProjectFile class

    class CProjectFile
    {
       ...
    };
    
        Q_DECLARE_METATYPE(CProjectFile)
    
        qRegisterMetaType<CProjectFile>("CProjectFile");//Do this if you need signal/slots
    
        qRegisterMetaTypeStreamOperators<QList<CProjectFile> >("CProjectFileList");
    

    See also QT Doc for stream operators