Introduction
Create a read-write configuration file class in singleton mode.
Features:
1. Singleton
2. Automatic memory recycling
3. Automatic configuration file creation
4. Read and write configuration content
(Code download is provided at the bottom of the article)
Code
head File
#ifndef ConfigInfomation_H
#define ConfigInfomation_H
#include <QFile>
#include <QObject>
#include <QSettings>
#define CONFIGINFOMATION ConfigInfomation::GetConfigInfomation()
const QString ConfigInfomationFilePath = "./ConfigInfomation.ini";
class ConfigInfomation : public QSettings
{
Q_OBJECT
public:
static ConfigInfomation *GetConfigInfomation();
void TCP_SET(const QString &,const unsigned int &);
void TCP_GET(QString &,unsigned int &);
private:
ConfigInfomation(QObject *parent = nullptr);
class GC
{
public:
~GC()
{
if(ConfigInfomation::configInfomation)
{
delete ConfigInfomation::configInfomation;
}
ConfigInfomation::configInfomation = nullptr;
}
};
private:
static ConfigInfomation *configInfomation;
static ConfigInfomation::GC gc;
};
#endif
CPP file
#include "ConfigInfomation.h"
ConfigInfomation *ConfigInfomation::configInfomation = nullptr;
ConfigInfomation::GC ConfigInfomation::gc;
ConfigInfomation *ConfigInfomation::GetConfigInfomation()
{
if(!configInfomation)
configInfomation = new ConfigInfomation;
return configInfomation;
}
void ConfigInfomation::TCP_SET(const QString &ip, const unsigned int &port)
{
beginGroup("TCP");
setValue("Ip",ip);
setValue("Port",port);
endGroup();
}
void ConfigInfomation::TCP_GET(QString &ip, unsigned int &port)
{
beginGroup("TCP");
ip = value("Ip").toString();
port = value("Port").toUInt();
endGroup();
}
ConfigInfomation::ConfigInfomation(QObject *parent) : QSettings(ConfigInfomationFilePath, QSettings::IniFormat, parent)
{
if (!QFile::exists(ConfigInfomationFilePath))
{
beginGroup("TCP");
setValue("Ip", "127.0.0.1");
setValue("Port", 8080);
endGroup();
}
}
Test code
#include "ConfigInfomation.h"
测试代码
QString ip;
unsigned int port;
CONFIGINFOMATION->TCP_GET(ip,port);
qDebug() << "111111:" << ip << " " << port << endl;
CONFIGINFOMATION->TCP_SET("192.168.1.1",9527);
CONFIGINFOMATION->TCP_GET(ip,port);
qDebug() << "222222:" << ip << " " << port << endl;
Test code screenshot
attention
attention
Search " Qt_io_ " or " Qt Developer Center " on WeChat public account to learn more about Qt and C++ development knowledge.
Author-jxd