qt创建.ini配置文件

.ini配置文件用于设置系统的某些参数,在系统设置发生某些改动时,也需要对.ini文件进行修改。


步骤:
1、对配置文件进行检查,如果不存在则按初始值创建新的配置文件,如果内容不完整或打开失败也按初始值加载。

//检查配置文件
bool App::checkConfig()
{
    //如果配置文件不存在,则按初始值新建
    QFile file(App::ConfigFile);
    if(file.size() == 0)
    {
        App::writeConfig();
        return false;
    }

    //如果配置文件不完整,则按初始值新建
    if(file.open(QIODevice::ReadOnly))
    {
        bool ok = true;
        while(!file.atEnd())
        {
            QString line = file.readLine();
            line = line.replace("\r","");
            line = line.replace("\n","");
            QStringList list = line.split("=");

            if(list.count() == 2)
            {
                if(list.at(1) == "")
                {
                    ok = false;
                    file.close();
                    break;
                }
            }
        }

        if(!ok)
        {
            App::writeConfig();
            return false;
        }
    }
    else
    {
        App::writeConfig();
        return false;
    }

    return true;
}


2、以键值对形式写入

//写入配置文件
void App::writeConfig()
{
    QSettings set(App::ConfigFile,QSettings::IniFormat);

    set.beginGroup("NetConfig");
    set.setValue("IP",App::NetIp);
    set.setValue("Port",App::NetPort);
    set.endGroup();

    set.beginGroup("DBConfig");
    set.setValue("Type",App::DBType);
    set.setValue("User",App::DBUser);
    set.setValue("Password",App::DBPassword);
    set.setValue("DBName",App::DBName);
    set.endGroup();
}


3、读取同样以键值对形式读取

//读取配置文件
void App::readConfig()
{
    if(!checkConfig())
        return;

    QSettings set(App::ConfigFile,QSettings::IniFormat);

    set.beginGroup("NetConfig");
    App::NetIp = set.value("IP",App::NetIp).toString();
    App::NetPort = set.value("Port",App::NetPort).toString();
    set.endGroup();

    set.beginGroup("DBConfig");
    App::DBType = set.value("Type",App::DBType).toString();
    App::DBUser = set.value("User",App::DBUser).toString();
    App::DBPassword = set.value("Password",App::DBPassword).toString();
    App::DBName = set.value("DBName",App::DBName).toString();
    set.endGroup();

    qDebug()<< App::NetIp;
    qDebug()<< App::NetPort;
    qDebug()<< App::DBType;
    qDebug()<< App::DBUser;
    qDebug()<< App::DBPassword;
    qDebug()<< App::DBName;
}


4、效果图
在这里插入图片描述

  • 2
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值