QSettings使用

创建配置文件操作对象

1、带路径

QSettings settings("./config.ini", QSettings::IniFormat); 

2、不带路径

配置文件路径默认为C:\Users\用户名\AppData\Roaming\organization\application.ini

方式一

QSettings settings("organization", "application");   //organization:公司名称  application:应用名称 可根据自己需求更改
settings.setDefaultFormat(QSettings::IniFormat);

方式二

QCoreApplication::setOrganizationName("organization");
QCoreApplication::setApplicationName("application");
QSettings settings;
settings.setDefaultFormat(QSettings::IniFormat);

推荐使用方式二,在main函数中调用QCoreApplication::setOrganizationName()QCoreApplication::setApplicationName()后,其他地方使用QSettings时可省略传参

写配置文件

QSettings settings;
settings.setValue("General/color", "#7e2598");
settings.setValue("General/savePath", "D:/Users");

// 注释部分代码效果和上面一致
// settings.beginGroup("General");
// settings.setValue("color", "#7e2598");
// settings.setValue("savePath", "D:/Users");
// settings.endGroup();

settings.setValue("General", 1);
settings.setValue("sofa", true);
settings.setValue("tv", false);

配置文件内容为

[General]
color=#7e2598
savePath=D:/Users

General=1
sofa=true
tv=false

读配置文件

QSettings settings;
QString value = settings.value(QString("General/color")).toString();    //value = "#7e2598"
value = settings.value(QString("General/savePath")).toString();         //value = "D:/Users"
int iValue = settings.value(QString("General")).toInt();                //iValue = 1
bool bValue = settings.value(QString("sofa")).toBool();                 //bValue = true
bValue = settings.value(QString("tv")).toBool();                        //bValue = false

删除配置项

QSettings settings;
settings.remove("General");

// 注释部分代码效果和上面一致
// settings.beginGroup("General");
// settings.remove("");
// settings.endGroup();

QStringList keys = settings.allKeys();
// keys: ["sofa", "tv"]
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页