PDA

View Full Version : Serializing QHash to a QByteArray



PeterThePuter
17th December 2010, 18:36
Hey all,

I am having some trouble serializing a QHash. Following this snippit (http://qt.onyou.ch/2010/10/19/62/) I attempted this:


#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;

}

However, when I run it, qDebug() spits this out:

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

What am I doing wrong?

Thanks!
-J

franz
17th December 2010, 19:05
Did you read your code? ds is defined as WriteOnly. You are then trying to output it to qDebug(). You cannot do that. One could even wonder how you would expect it to be output to qDebug()...

PeterThePuter
17th December 2010, 20:58
**Facepalm** Thanks!

the QByteArray ba is still empty however:


qDebug() << ba.isEmpty()
gives true.

wysota
17th December 2010, 23:19
Maybe the data isn't flushed to the byte array yet? See if this works:

#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;
} // here the stream gets destroyed so it has to flush whatever it caches
qDebug() << ba;
}