前言
每次都使用QSeting去读取和写入,感觉还是麻烦,于是自己封装了一个类。
源码
managerIniFile.h
cpp
#ifndef MANAGERINIFILE_H
#define MANAGERINIFILE_H
#include <QString>
#include <QDebug>
#include <QSettings>
#include <QCoreApplication>
/**
* @brief 配置文件管理类
*/
class ManagerIniFile
{
public:
ManagerIniFile();
void SetIniPath(QString strIniFileName);
void WriteSetting(QString strGroup, QString strValueName,QString strValue);
QString ReadSetting(QString strGroup, QString strValueName, QString defaultStr = QString(""));
private:
QString defaultStrIniFileName;
QString strIniFileName;
QSettings *m_settings;
};
#endif // MANAGERINIFILE_H
// 使用案例:
// QString strIniPath = QCoreApplication::applicationDirPath();
// strIniPath += "/";
// strIniPath += "config.ini";
// ManagerIniFile info;
// 可省:info.SetIniPath(strIniPath);
managerIniFile.cpp
cpp
#include "managerIniFile.h"
ManagerIniFile::ManagerIniFile()//:m_settings(defaultStrIniFileName,QSettings::IniFormat)
{
defaultStrIniFileName = QCoreApplication::applicationDirPath() + "/" + "config.ini";
strIniFileName = defaultStrIniFileName;
m_settings = new QSettings(defaultStrIniFileName, QSettings::IniFormat);
}
void ManagerIniFile::SetIniPath(QString strIniFileName)
{
m_settings->setUserIniPath(strIniFileName);
}
void ManagerIniFile::WriteSetting(QString strGroup, QString strValueName,QString strValue)
{
// qDebug()<<"save ini file";
m_settings->beginGroup(strGroup);
m_settings->setValue(strValueName,strValue);
m_settings->endGroup();
}
QString ManagerIniFile::ReadSetting(QString strGroup, QString strValueName, QString defaultStr)
{
QString str = QString("%1/%2").arg(strGroup,strValueName);
if(!(m_settings == nullptr))delete m_settings;
m_settings = new QSettings(defaultStrIniFileName, QSettings::IniFormat);
QString res = m_settings->value(str).toString();
if(res==QString(""))
return defaultStr;
return res;
}
使用案例
- 默认配置文件是config.ini,可以手动更改:
// 使用案例:
QString strIniPath = QCoreApplication::applicationDirPath();
strIniPath += "/";
strIniPath += "config.ini";
ManagerIniFile info;
可省:info.SetIniPath(strIniPath);
- 读取:
cpp
ManagerIniFile iniManager;
QString tmp = iniManager.ReadSetting("VIDEOPARA1",tr("SHOWCTRL"));
QString tmp = iniManager.ReadSetting("VIDEOPARA1",tr("SHOWCTRL"),QString::number(1)).toUInt();
- 写入:
cpp
ManagerIniFile iniManager;
iniManager.WriteSetting("VIDEOPARA1",tr("SHOWCTRL"),"2");