Jay
Jay

Reputation: 2902

Serializing QHash to QByteArray

I am trying to serialize a QHash object and store it in a QByteArray (to be sent using QUDPSocket or QTCPSocket).

My current attempt looks like this:

// main.cpp
#include <QtCore/QCoreApplication>
#include <QHash>
#include <QVariant>
#include <QDebug>

int main(int argc, char *argv[])
{

    QHash<QString,QVariant> hash;
    hash.insert("Key1",1);
    hash.insert("Key2","thing2");

    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);
    ds << hash;
    qDebug() << ds;

}

When this runs I get this out of qDebug():

QIODevice::read: WriteOnly device
QIODevice::read: WriteOnly device
QIODevice::read: WriteOnly device
QVariant(, ) 

The documentation says that this should write to the byte array, but obviously that isn't happening here. What am I doing wrong?

Qt 4.7.1 on OS-X

Thanks! -J

Upvotes: 4

Views: 4309

Answers (2)

Mohammad Sheykholeslam
Mohammad Sheykholeslam

Reputation: 1437

You can Implement you program like this code:

QHash<QString,QVariant> options;
options["string"] = "my string";
options["bool"] = true;

QByteArray ar;

//Serializing
QDataStream out(&ar,QIODevice::WriteOnly);   // write the data
out << options;

//setting a new value
options["string"] = "new string";

//Deserializing
// read the data serialized from the file
QDataStream in(&ar,QIODevice::ReadOnly);   
in >> options;

qDebug() << "value: " << options.value("string");

ref

Upvotes: 1

Dave Mateer
Dave Mateer

Reputation: 17956

The reason it is failing is because it is trying to read from a write-only stream. The sequence is:

qDebug() << ds;
--> QVariant::QVariant(QDataStream &s)
  --> QDataStream& operator>>(QDataStream &s, QVariant &p)
   --> void QVariant::load(QDataStream &s)

That last method (and some more downstream) try to read from the data stream to convert its contents into a QVariant for display in qDebug. In other words, your actual code is fine; the debugging check is causing the failure.

You could check the contents of the byte array with something like:

qDebug() << ba.length() << ba.toHex();

Upvotes: 4

Related Questions