天天看点

Qt读写ini文件的C++类

一、头文件

#ifndef PRJINI_H

#define PRJINI_H

class QPrjIni

{

private://禁止实例化

   QPrjIni();

public:

   static bool write(QString section, QString key, QString value, QString path);

   static bool read(QString section, QString key, QString &value, QString path);

};

#endif // PRJINI_H

二、源文件

#include "prjini.h"

#include <qsettings.h>

QPrjIni::QPrjIni()

{

}

bool QPrjIni::write(QString section, QString key, QString value, QString path)

   if (path.isEmpty() || key.isEmpty())

   {

       return false;

   }

   else

       //创建配置文件操作对象

       QSettings *config = new QSettings(path, QSettings::IniFormat);

       //将信息写入配置文件

       config->beginGroup(section);

       config->setValue(key, value);

       config->endGroup();

       //内存释放

       delete config;

       return true;

bool QPrjIni::read(QString section, QString key, QString &value, QString path)

   value = QString("");

       //读取用户配置信息

       value = config->value(section + "/" + key).toString();

}

三、应用案例

//软件名称与版本

   QString softname;

   QString softver;

   QString path = qApp->applicationDirPath() + "/config.ini";

   QPrjIni::read("setting", "softname", softname, path);

   QPrjIni::read("setting", "softver", softver, path);

继续阅读