class classfiyInfo { public: QColor _color; bool _isSelect;}序列化到文件
时间: 2024-11-20 09:44:09 浏览: 5
关于Qt的常用类介绍
这个`classifyInfo`类包含两个成员变量:`_color`,表示颜色信息,类型为`QColor`; `_isSelect`,是一个布尔值,表示是否选中。要将此类的对象序列化(保存)到文件中,通常我们会使用XML、JSON或者二进制流(如protobuf或pickle)。这里以XML为例,因为它的格式清晰易读:
```cpp
#include <QXmlStreamWriter>
#include <fstream>
void serializeClassifyInfoToFile(const classifyInfo& info, const QString& filePath) {
QXmlStreamWriter writer(QXmlStreamDevice(new QFile(filePath)));
if (!writer.setAutoFormatting(true)) {
qCritical("Failed to set auto formatting");
return;
}
writer.writeStartDocument();
writer.writeStartElement("classifyInfo");
writer.writeAttribute("color", info._color.name());
writer.writeBoolAttribute("isSelect", info._isSelect);
writer.writeEndElement(); // End of classifyInfo element
writer.writeEndDocument();
if (!writer.isFinished()) {
qCritical("Failed to write XML document");
} else {
qDebug() << "Serialized classifyInfo to file successfully.";
}
}
// 使用示例:
classifyInfo ci = {QColor("red"), true};
serializeClassifyInfoToFile(ci, "classify_info.xml");
```
当你需要从文件恢复数据时,可以创建一个新的`classifyInfo`实例并反序列化:
```cpp
classifyInfo deserializedInfo;
QFile file("classify_info.xml");
if (file.open(QIODevice::ReadOnly)) {
QXmlStreamReader reader(&file);
while (!reader.atEnd()) {
if (reader.isStartElement()) {
if (reader.name() == "classifyInfo") {
reader.readNext();
deserializedInfo._color = QColor(reader.text().toStdString());
deserializedInfo._isSelect = reader.readBool();
}
}
reader.readNext();
}
}
```
阅读全文