Convert QByteArray to object and vice versa
I have a data structure:
Code:
typedef struct
{
int Port;
} VideoSource;
Q_DECLARE_METATYPE( VideoSource )
All I want to do is be able to convert this to a byte array in order to send on a socket, and get the object back (deserialize) on the other end. So I am doing this:
Code:
int videoSourceMetaTypeId = qRegisterMetaType< VideoSource >();
...
...
VideoSource vs;
vs.IpAddress = "127.0.0.1";
vs.Port = 5678;
videoSourceAsVariant.setValue( vs );
QByteArray videoSourceBytes
= videoSourceAsVariant.
toByteArray();
int numBytes = videoSourceBytes.count(); // this is 0
Not sure why the byte array's size ends up being 0.
So how do I get the object back? Was trying this but obviously it's wrong...
Code:
if( testVar.canConvert< VideoSource >() ) // returns false
{
VideoSource testVs = testVar.value< VideoSource >();
}
Re: Convert QByteArray to object and vice versa
It's because QVariant doesn't know how to convert your object to byte array and as far as I remember there is no way to teach it do it.
What you should do is reimplement operators (<< and >>) for QDataStream to be able to stream your object into a datastream that can operate on a byte array.
Re: Convert QByteArray to object and vice versa
Ok. I am going to work on that. Do you know why this doesn't compile?
VideoSource.h:
Code:
#ifndef VideoSource_h_
#define VideoSource_h_
#include <QString>
#include <QDataStream>
#pragma pack 1
typedef struct
{
quint16 Port;
} VideoSource;
Q_DECLARE_METATYPE( VideoSource )
#endif
VideoSource.cpp:
Code:
#include "VideoSource.h"
{
return stream;
}
{
return stream;
}
I get errors like:
Error 2 error C3646: 'QDataStream' : unknown override specifier
Error 3 error C2143: syntax error : missing ';' before '&'
Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 6 error C2556: 'int &operator <<(QDataStream &,const VideoSource &)' : overloaded function differs only by return type from 'QDataStream &operator <<(QDataStream &,const VideoSource &)'
Error 7 error C2371: 'operator <<' : redefinition; different basic types
Re: Convert QByteArray to object and vice versa
Looks like you need:
#include <QDataStream>
[EDIT]
I see you have that in your header file. [/EDIT]
[EDIT2] Whats with the ; on line 9 of your header file [EDIT2]
Re: Convert QByteArray to object and vice versa
Took out the following line and it worked:
Q_DECLARE_METATYPE( VideoSource )