gpt4 book ai didi

c++ - Qt - 如何为我的应用程序保存数据

转载 作者:太空狗 更新时间:2023-10-29 20:40:12 25 4
gpt4 key购买 nike

我是 Qt 的新手,我在了解如何从您的应用程序中保存/加载数据时遇到了问题。

我正在创建一个日历应用程序,并且必须保存不同的类,例如:死亡期限、约会、生日等。

我找到了这个教程 http://qt-project.org/doc/qt-4.8/tutorials-addressbook-part6.html但它只描述了如何保存一种类。

所以我想知道你是否可以帮助我,因为我不知道如何以这种方式保存/加载多个类,我不需要它的一些详细描述(当然会很感激)但只需要一个轻轻推向正确的方向。

因为本教程中没有任何地方解释如何保存多个类:(

编辑:此程序适用于 PC(学校项目)

最佳答案

您可以定义自定义类并为其实现流运算符:

class CustomType
{
public:

CustomType()
{
paramter1=0;
paramter2=0;
paramter3="";

}
~CustomType(){}

int paramter1;
double parameter2;
QString parameter3;
};


inline QDataStream& operator<<( QDataStream &out, const CustomType& t )
{
out<<t.paramter1;
out<<t.paramter2;
out<<t.paramter3;


return out;
}
inline QDataStream& operator>>( QDataStream &in, CustomType& t)
{
in>>t.paramter1;
in>>t.paramter2;
in>>t.paramter3;

return in;
}

在流式传输类之前启动应用程序时,您应该在代码中的某处注册类的流运算符。这可以在主窗口的构造函数中完成:

qRegisterMetaTypeStreamOperators<CustomType>("CustomType");

现在您可以将类的对象保存到文件或从文件加载对象。

将自定义类的一些对象保存到文件中:

QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}


QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_8);
out << object1;
out << object2;

从文件加载自定义类的对象:

QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}


QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_8);
in >> object1;
in >> object2;

注意读写文件的顺序要一致。

关于c++ - Qt - 如何为我的应用程序保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25113596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com