.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、效果图