Results 1 to 5 of 5

Thread: Convert QByteArray to object and vice versa

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Apr 2009
    Posts
    63
    Thanks
    1
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4 Qt/Embedded
    Platforms
    Windows

    Default Convert QByteArray to object and vice versa

    I have a data structure:

    Qt Code:
    1. typedef struct
    2. {
    3. QString IpAddress;
    4. int Port;
    5. } VideoSource;
    6.  
    7. Q_DECLARE_METATYPE( VideoSource )
    To copy to clipboard, switch view to plain text mode 

    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:

    Qt Code:
    1. int videoSourceMetaTypeId = qRegisterMetaType< VideoSource >();
    2. ...
    3. ...
    4. VideoSource vs;
    5. vs.IpAddress = "127.0.0.1";
    6. vs.Port = 5678;
    7. QVariant videoSourceAsVariant;
    8. videoSourceAsVariant.setValue( vs );
    9. QByteArray videoSourceBytes = videoSourceAsVariant.toByteArray();
    10. int numBytes = videoSourceBytes.count(); // this is 0
    To copy to clipboard, switch view to plain text mode 

    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...

    Qt Code:
    1. QVariant testVar( videoSourceBytes );
    2. if( testVar.canConvert< VideoSource >() ) // returns false
    3. {
    4. VideoSource testVs = testVar.value< VideoSource >();
    5. }
    To copy to clipboard, switch view to plain text mode 

  2. The following user says thank you to DiamonDogX for this useful post:


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.