QList <qstring> and QDataStream</qstring>
-
Trying QDataStream to record QList and then retrieve it.
QList <QString> l = {"a", "bb", "ccc"}; qDebug() << l; QByteArray arr; QDataStream in(&arr, QIODevice::WriteOnly); in.setVersion(QDataStream::Qt_DefaultCompiledVersion); in << l; QList <QString> l2; QDataStream out(&arr, QIODevice::ReadOnly); out >> l2; qDebug() << l2;
It's empty out. Why?
-
User data types need to be sent to the flow: 1. Determine the operator of entry and withdrawal. It's simple:
friend QDataStream &operator <<(QDataStream &in, const MyClass &_obj) { in << _obj.m_field1; in << _obj.m_field2; in << _obj.m_field3; in << _obj.m_field4; return in; }
friend QDataStream &operator >>(QDataStream &out, MyClass &_obj)
{
out >> _obj.m_field1;
out >> _obj.m_field2;
out >> _obj.m_field3;
out >> _obj.m_field4;
return out;
}
There's a minus here, if we've decided to add another field, the previously recorded data cannot be read. I mean, there's no backup. To avoid this, a more complex option can be used:
friend QDataStream &operator <<(QDataStream &in, const MyClass &_obj)
{
QVariantMap m;
m["field1"] = QVariant::fromValue(_obj.m_field1);
m["field2"] = QVariant::fromValue(_obj.m_field2);
m["field3"] = QVariant::fromValue(_obj.m_field3);
m["field4"] = QVariant::fromValue(_obj.m_field4);
in << m;
return in;
}friend QDataStream &operator >>(QDataStream &out, MyClass &_obj)
{
QVariantMap m;
out >> m;
_obj.m_field1 = m["field1"].toInt();
_obj.m_field2 = m["field2"].toString();
_obj.m_field3 = m["field3"].toDouble();
_obj.m_field4 = m["field4"].toBool();
return out;
}
Or even a little easier:
template <class T>
static void convert(const QVariant &_val, T &result)
{
result = _val.value<T>();
}friend QDataStream &operator >>(QDataStream &out, MyClass &_obj)
{
QVariantMap m;
out >> m;
convert(m["field1"], _obj.m_field1);
convert(m["field2"], _obj.m_field2);
convert(m["field3"], _obj.m_field3);
convert(m["field4"], _obj.m_field4);return out;
}
In such a case, the fields may be added/delayed and all previously recorded data may be considered.
2. Specify the qt meta-system that a user type of data can be streamed. To this end, prior to the flow recording process, call the function:
qRegisterMetaTypeStreamOperators<MyClass>("MyClass");
All registrations are usually made immediately after the programme is launched.
If we're gonna write a list, we'll also call it:qRegisterMetaTypeStreamOperators<QList<MyClass>>("QList<MyClass>");
qRegisterMetaTypeStreamOperators<QVector<MyClass>>("QVector<MyClass>");
If a member of the class is also a user type, it also needs to define the flow recording function and cause qRegisterMetaTypeStreamOperators.
For basic Qt types qRegisterMetaTypeStreamOperators, usually completed, so it's weird that you don't have QList Runway.