当前位置:   article > 正文

Qt序列化与反序列化(QDataStream)_qdatastream 结构体序列化

qdatastream 结构体序列化

功能:Qt序列化与发序列化的实现(QDataStream)
用途:UI界面自定义数据结构的保存于读取

```cpp
struct Body

{
    double weight;
    double height;
};
//结构体
struct People
{
    int age;
    Body dBody;//结构体
    vector<QString> vecfamily;//vector
    //序列化
    friend QDataStream &operator<<(QDataStream& input,const People &iteam)
    {
        //vector 数据类型需要用vector<People>::fromStdVector 转一下
        //如果是QList则不需要直接插入
        QVector<QString> strvecfamily = QVector<QString>::fromStdVector(iteam.vecfamily);
        input << iteam.age << iteam.dBody.height << iteam.dBody.weight\
              << strvecfamily;
        return input;
    }
    //反序列化
    friend QDataStream &operator>>(QDataStream& output,People& iteam)
    {
        QVector<QString> vecfamily;
        output >> iteam.age >>iteam.dBody.height >> iteam.dBody.weight >> vecfamily;
        iteam.vecfamily = vecfamily.toStdVector();
        return output;
    }
};
数据的使用
People p1;
    p1.age = 12;
    p1.dBody.height = 150.8;
    p1.dBody.weight = 50;
    p1.vecfamily.push_back("sister");
    p1.vecfamily.push_back("mother");
    p1.vecfamily.push_back("father");
    QFile file("./stream.bat");
    if(!file.open(QIODevice::WriteOnly))
    {
        return ;
    }
    QDataStream input(&file);
    input << p1;
    file.close();
    People p2;
    QFile file1("./stream.bat");//.bat文件为二进制文件
    if(!file1.open(QIODevice::ReadOnly))
    {
        return ;
    }
    QDataStream output(&file1);
    output << p2;
    file.close();

    output >> p2;
    qDebug()<<p2.age<<p2.dBody.height<<p2.dBody.weight\
           <<p2.vecfamily;//结果12 150.8 50 std::vector("sister", "mother", "father")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

原文链接:https://www.cnblogs.com/that-boy-done/p/10739097.html
非原创,侵权必删!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/162929
推荐阅读
相关标签
  

闽ICP备14008679号