头文件
#ifndef CONFIGFILEPARSER_H
#define CONFIGFILEPARSER_H
#include <QVariant>
class QSettings;
/*
*配置文件解析类,适配器设计模式
*/
class ConfigFileParser
{
public:
ConfigFileParser();
~ConfigFileParser();
QString getCurrentPath();
QString getConfigFile();
void setValue(const QString &key, const QVariant &value);
QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const;
void remove(const QString &key);
void sync(); //同步操作,可使写入的信息立即生效
private:
QSettings *m_configIniWrite;
QString m_currentPath;
QString m_configFile;
};
#endif // CONFIGFILEPARSER_H
CPP文件
#include <QDir>
#include <QSettings>
#include <QTextCodec>
#include "configfileparser.h"
ConfigFileParser::ConfigFileParser()
{
m_currentPath = QDir::home().path() + "/.local/share";
m_configFile = m_currentPath + "/config.ini";
m_configIniWrite = new QSettings(m_configFile, QSettings::IniFormat);
m_configIniWrite->setIniCodec(QTextCodec::codecForName("UTF-8"));
}
ConfigFileParser::~ConfigFileParser()
{
if (m_configIniWrite != NULL)
{delete m_configIniWrite;m_configIniWrite= NULL;}
}
void ConfigFileParser::sync()
{m_configIniWrite->sync();}
QString ConfigFileParser::getCurrentPath()
{return this->m_currentPath;}
QString ConfigFileParser::getConfigFile()
{return this->m_configFile;}
void ConfigFileParser::setValue(const QString &key, const QVariant &value)
{m_configIniWrite->setValue(key,value);}
QVariant ConfigFileParser::value(const QString &key, const QVariant &defaultValue) const
{return m_configIniWrite->value(key,defaultValue);}
void ConfigFileParser::remove(const QString &key)
{m_configIniWrite->remove(key);}
另外,调用时,应该如下:
ConfigFileParser configFileParser;//栈变量,自动释放。
注意:如果想要改变配置文件名称或位置,可以自行优化,也很简单。