随笔 - 49  文章 - 0  评论 - 6  阅读 - 10万

使用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   朱迎春  阅读(518)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示