Ralf Wickum
Ralf Wickum

Reputation: 3294

Serializing QHash with own Class?

I have a QHash<const QString id, MyClass> , whereas MyClass is just a collection of some QString quint8 values with getters and setters. MyClass also has a QDataStream &operator<<(QDataStream &ds, const MyClass &obj) overwritten, there.

To serialize I use:

typedef QHash<const QString, MyClass> MyClassHash;
//..
QDataStream &operator<<(QDataStream &ds, const MyClassHash &obj) {

    QHashIterator<const QString, MyClass> i(obj);

    while(i.hasNext())
    {
        i.next();
        QString cKey = i.key();
        ds << cKey << i.value();
    }

    return ds;
}

Now, I am confused with the other:

QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
    obj.clear();

    // ?    

    return ds;
}

I would I know the legth of that serialized QHash ?

Upvotes: 0

Views: 524

Answers (3)

peppe
peppe

Reputation: 22826

You do not provide operator<< and operator>> for QHash; their implementation is already provided for you by Qt.

As long as both your key type and your value type are serializable using QDataStream, then you're good to go:

class MyClass
{
    int i;
    friend QDataStream &operator<<(QDataStream &ds, const MyClass &c);
    friend QDataStream &operator>>(QDataStream &ds, MyClass &c);
};

QDataStream &operator<<(QDataStream &ds, const MyClass &c)
{
    ds << c.i;
    return ds;
}
QDataStream &operator>>(QDataStream &ds, MyClass &c)
{
    ds >> c.i;
    return ds;
}

int main() 
{
    QHash<QString, MyClass> hash;
    QDataStream ds;
    // doesn't do anything useful, but it compiles, showing you
    // that you don't need any custom streaming operators
    // for QHash
    ds << hash;
    ds >> hash;
}

Upvotes: 1

Murat
Murat

Reputation: 756

Whatabout the QDataStream::status :

QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
  obj.clear(); // clear possible items

  Myclass cMyCls;

  while (!ds.status()) { // while not finished or corrupted
    ds >> cKey >> cMyCls;
    if (!cKey.isEmpty()) { // prohibits the last empty one
      obj.insert(cKey, cMyCls);
    }
  } 

  return ds;
}

Upvotes: 1

fghj
fghj

Reputation: 9404

Obviously, there are two ways to do things:

  1. In operator<< before save items of QHash you should save QHash::size
  2. At the end of operator<< save some invalid QString, for example empty QString, and in operator>>, stop reading when we meet such value.

Upvotes: 0

Related Questions