QT之配置文件编写工具类
前言
其实不为了什么,发一个准备自己用却还没有用的工具类吧!哈哈~~注意是我还没用过的,不知道有没有bug。
源代码
头文件
#ifndef QCONFIGBUILDER_H
#define QCONFIGBUILDER_H
#include <QString>
#include <QVariant>
/*!
* \class QConfigBuilder
* \brief The QConfigBuilder class is a configuration file operation tool class, which can make users more convenient to operate configuration files.
*/
class QConfigBuilder
{
public:
QConfigBuilder();
QConfigBuilder(QString configPath);
/*!
* \brief Set configuration file path.
* \param configPath: configuration file path
*/
void setConfigPath(QString configPath);
/*!
* \brief Create configuration file.
* \param filePath: configuration file path
*/
void createIniFile(QString filePath);
/*!
* \brief Get parameter value from configuration file.
* \param groupName: parameter group name
* \param keyName: parameter name
* \return
*/
QVariant getValue(QString groupName, QString keyName);
/*!
* \brief Set parameter value from configuration file.
* \param groupName: parameter group name
* \param keyName: parameter name
* \param value: parameter value
*/
void setValue(QString groupName, QString keyName, QVariant value);
/*!
* \brief remove parameter from configuration file.
* \param groupName: parameter group name
* \param keyName: parameter name
*/
void removeKey(QString groupName, QString keyName);
private:
QString configPath;
};
#endif // QCONFIGBUILDER_H
源文件
#include "qconfigbuilder.h"
#include <QFile>
#include <QSettings>
QConfigBuilder::QConfigBuilder()
{
}
QConfigBuilder::QConfigBuilder(QString configPath)
{
this->setConfigPath(configPath);
}
void QConfigBuilder::setConfigPath(QString configPath)
{
if(this->configPath != configPath)
{
this->configPath = configPath;
createIniFile(configPath);
}
}
void QConfigBuilder::createIniFile(QString filePath)
{
QFile file(filePath);
file.open(QFile::ReadWrite);
if (file.isOpen())
{
file.close();
}
}
QVariant QConfigBuilder::getValue(QString groupName, QString keyName)
{
QSettings set(configPath, QSettings::IniFormat);
QVariant value = set.value(QString("%0/%1").arg(groupName, keyName));
return value;
}
void QConfigBuilder::setValue(QString groupName, QString keyName, QVariant value)
{
QSettings set(configPath, QSettings::IniFormat);
set.setValue(QString("%0/%1").arg(groupName, keyName), value);
//set.beginGroup(groupName);
//set.setValue(keyName, value);
//set.endGroup();
}
void QConfigBuilder::removeKey(QString groupName, QString keyName)
{
QSettings set(configPath, QSettings::IniFormat);
set.remove(QString("%0/%1").arg(groupName, keyName));
}