Qt之单例 - 读写配置文件

简介

     创建单例模式的读写配置文件类。

     特点:

          1、单例类

          2、内存自动回收

          3、配置文件自动创建

          4、读写配置内容


(文章底部提供代码下载)

代码

     头文件

#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文件

#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();
    }
}

     测试代码

#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;
 	

     测试代码截图
在这里插入图片描述

关注

源码

关注

微信公众号搜索"Qt_io_"或"Qt开发者中心"了解更多关于Qt、C++开发知识.。

笔者 - jxd

猜你喜欢

转载自blog.csdn.net/automoblie0/article/details/107955750
今日推荐