創(chuàng)建配置文件操作對象
1柳琢、帶路徑
QSettings settings("./config.ini", QSettings::IniFormat);
2、不帶路徑
配置文件路徑默認為C:\Users\用戶名\AppData\Roaming\organization\application.ini
方式一
QSettings settings("organization", "application"); //organization:公司名稱 application:應(yīng)用名稱 可根據(jù)自己需求更改
settings.setDefaultFormat(QSettings::IniFormat);
方式二
QCoreApplication::setOrganizationName("organization");
QCoreApplication::setApplicationName("application");
QSettings settings;
settings.setDefaultFormat(QSettings::IniFormat);
推薦使用方式二募谎,在main函數(shù)中調(diào)用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);
配置文件內(nèi)容為
[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"]