Serialization with Qt(使用 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 进行序列化
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
