使用QSettings操作INI配置文件

环境:Win10+VS2015+Qt5.9.8

C++代码:

    // 配置文件:可执行路径\config\main.ini,如果没有config子目录会自动创建
    QSettings settings(QString("%1%2").arg(QCoreApplication::applicationDirPath(), "\\config\\main.ini"), QSettings::Format::IniFormat);

    settings.clear();                            // 清除已有的所有配置,慎用
    settings.setValue("Key1", "Value1");        // 缺省Section是[General]
    settings.setValue("Key2", true);
    settings.setValue("Key3", "中文");            // 中文保存编码值\x4e2d\x6587
    settings.setValue("Section1/Key1", "Value1");
    settings.setValue("Section1/Key2", true);
    settings.setValue("Section1/Key3", "中文");
    settings.setValue("Section2/Key1", "Value1");
    settings.setValue("Section2/Key2", true);
    settings.setValue("Section2/Key3", "中文,Eng,\"Eng\"");

    QString s = settings.value("Key3").toString();
    LOG_INFO("值:" << s.toStdString().c_str());

    // 存取列表
    QList<QVariant> list1 = { 1, "A,B", "我,你" };
    settings.setValue("Section2/Key4", QVariant(list1));
    QList<QVariant> list2 = settings.value("Section2/Key4").toList();

    // 存取键值对
    QMap<QString, QVariant> map1 = { { "mapkey1", 1 },{ "mapkey2", "哈哈" } };
    settings.setValue("Section2/Key5", QVariant(map1));
    QMap<QString, QVariant> map2 = settings.value("Section2/Key5").toMap();

对应INI文件:

[General]
Key1=Value1
Key2=true
Key3=\x4e2d\x6587

[Section1]
Key1=Value1
Key2=true
Key3=\x4e2d\x6587

[Section2]
Key1=Value1
Key2=true
Key3="\x4e2d\x6587,Eng,\"Eng\""
Key4=1, "A,B", "\x6211,\x4f60"
Key5=@Variant(\0\0\0\b\0\0\0\x2\0\0\0\xe\0m\0\x61\0p\0k\0\x65\0y\0\x32\0\0\0\n\0\0\0\x4T\xc8T\xc8\0\0\0\xe\0m\0\x61\0p\0k\0\x65\0y\0\x31\0\0\0\x2\0\0\0\x1)

 

posted on 2022-02-22 17:17  朱迎春  阅读(463)  评论(0编辑  收藏  举报