Simple custom QVariant serialization not working
-
I have implemented a custom QVariant type by registering the class with Q_DECLARE_METATYPE(Vector) and defining the stream operators.
Vector.h:
class Vector { public: Vector(); QString mFoo; }; Q_DECLARE_METATYPE(Vector) QDataStream& operator<<(QDataStream& stream, const Vector& v); QDataStream& operator>>(QDataStream& stream, Vector& v);
Vector.cpp:
#include "Vector.h" Vector::Vector() { } QDataStream& operator<<(QDataStream& stream, const GVector& v) { stream << v.mFoo; return stream; } QDataStream& operator>>(QDataStream& stream, Vector& v) { stream >> v.mFoo; return stream; }
Test code:
QMetaType metaType = QMetaType::fromName("Vector"); Q_ASSERT(metaType.hasRegisteredDataStreamOperators()); // PASSES Vector vector; vector.mFoo = "bar"; QVariant variant = QVariant::fromValue<Vector>(vector); QByteArray bytes; QDataStream stream(&bytes, QIODevice::WriteOnly); stream << variant; QDataStream stream2(&bytes, QIODevice::ReadOnly); QVariant variant2; stream >> variant2; Vector vector2 = variant2.value<Vector>(); Q_ASSERT(vector2.mFoo == "bar"); // FAILS
The vector is not restored correctly--in fact the variant is null when inspecting it. The stream read function is not even called.
Is there something I'm missing? I assumed this is how serialization with custom types were supposed to work.
-
You forgot qRegisterMetaTypeStreamOperators<>() : https://forum.qt.io/topic/1690/qvariant-save-load-unable-to-save-type-x/4
-
@Christian-Ehrlicher I'm using Qt 6, where that function has been removed. According to the docs the stream operators are detected automatically.
-
The you should at least call qRegisterMetaType<>().
-
@Christian-Ehrlicher I've tried that too, but it still doesn't work.
-
Christian Ehrlicher Lifetime Qt Championreplied to Per Ivar Bruheim on last edited by Christian Ehrlicher
I tried your code here (no copy and paste) with Qt6. 6 and it worked correct, even without qRegisterMetaType<>(). Will have to find out the difference.
/edit: please output the bytearray with qDebug to see if it was properly serialized.
-
@Per-Ivar-Bruheim said in Simple custom QVariant serialization not working:
QVariant variant2;
stream >> variant2;OK, you should correct this.
-
@Christian-Ehrlicher @Christian-Ehrlicher Thank you. Such an embarrasingly simple mistake.
-
-
This post is deleted!