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

Qt - How to save data for my application

本文关键字:应用程序 保存 数据 我的 Qt      更新时间:2023-10-16

我是Qt的新手,我有一个问题,如何从你的应用程序中保存/加载数据。

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

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

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

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

编辑:这个程序是为个人电脑(学校项目)

你可以定义你的自定义类并为它实现流操作符:

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;

注意读写文件的顺序应该是一样的