使用 Qt 进行序列化

时间:2022-11-21
本文介绍了使用 Qt 进行序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 Qt 库编写 GUI.在我的 GUI 中,我有一个巨大的 std::map.

I am programming a GUI with Qt library. In my GUI I have a huge std::map.

MyType"是一个具有不同类型字段的类.

"MyType" is a class that has different kinds of fields.

我想序列化 std::map.我怎样才能做到这一点?Qt 是否为我们提供了必要的功能?

I want to serialize the std::map. How can I do that? Does Qt provides us with neccesary features?

推荐答案

QDataStream 处理各种 C++ 和 Qt 数据类型.完整列表可在 http://doc.qt.io/qt-4.8/datastreamformat.html.我们还可以通过重载 << 来添加对我们自己的自定义类型的支持.和 >> 运算符.以下是可与 QDataStream 一起使用的自定义数据类型的定义:

QDataStream handles a variety of C++ and Qt data types. The complete list is available at http://doc.qt.io/qt-4.8/datastreamformat.html. We can also add support for our own custom types by overloading the << and >> operators. Here's the definition of a custom data type that can be used with QDataStream:

class Painting
{
public:
    Painting() { myYear = 0; }
    Painting(const QString &title, const QString &artist, int year) {
        myTitle = title;
        myArtist = artist;
        myYear = year;
    }
    void setTitle(const QString &title) { myTitle = title; }
    QString title() const { return myTitle; }
    ...
private:
    QString myTitle;
    QString myArtist;
    int myYear;
};
QDataStream &operator<<(QDataStream &out, const Painting &painting);
QDataStream &operator>>(QDataStream &in, Painting &painting);

以下是我们如何实现 <<操作员:

Here's how we would implement the << operator:

QDataStream &operator<<(QDataStream &out, const Painting &painting)
{
    out << painting.title() << painting.artist()
        << quint32(painting.year());
    return out;
}

要输出一幅画,我们只需输出两个 QString 和一个 quint32.在函数结束时,我们返回流.这是一个常见的 C++ 习惯用法,它允许我们使用 <<具有输出流的运算符.例如:

To output a Painting, we simply output two QStrings and a quint32. At the end of the function, we return the stream. This is a common C++ idiom that allows us to use a chain of << operators with an output stream. For example:

出<<绘画1<<绘画2<<绘画3;

out << painting1 << painting2 << painting3;

operator>>()的实现与operator<<()类似:

The implementation of operator>>() is similar to that of operator<<():

QDataStream &operator>>(QDataStream &in, Painting &painting)
{
    QString title;
    QString artist;
    quint32 year;
    in >> title >> artist >> year;
    painting = Painting(title, artist, year);
    return in;
}

本文来自:C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield

This is from: C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield

这篇关于使用 Qt 进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:非阻塞工作者 - 中断文件复制 下一篇:Qt:找不到 -lGL 错误

相关文章

最新文章