Qt QList<QString> serialization for database

别来无恙 提交于 2019-12-20 01:41:48

问题


I have a QList list. I want to insert it on the database. I didn't find any serializer method after some googling. If there any method / idea to serialize the list data for database?


回答1:


How about using QStringList instead of QList<QString> -

QStringList numberList_;    // instead of QList<QString>, use this
QString myString1 = "Hello";
QString myString2 = "World";
numberList_ << myString1;
numberList_ << myString2;

QByteArray byteArray;
QBuffer buffer(&byteArray);
QDataStream out(&buffer);
out << numberList_;

Probably QList<QString> should also work in place of QStringList. If it doesn't, well, you can convert it pretty easily to QStringList.

QDataStream, QBuffer, QByteArray and QStringList reference.




回答2:


Here is another option that is a bit more succinct:

QString serialize(QStringList stringList)
{
  QByteArray byteArray;
  QDataStream out(&byteArray, QIODevice::WriteOnly);
  out << stringList;
  return QString(byteArray.toBase64());
}

QStringList deserialize(QString serializedStringList)
{
  QStringList result;
  QByteArray byteArray = QByteArray::fromBase64(serializedStringList.toUtf8());
  QDataStream in(&byteArray, QIODevice::ReadOnly);
  in >> result;
  return result;
}


来源:https://stackoverflow.com/questions/9817918/qt-qlistqstring-serialization-for-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!