QSettings写General组会出现百分号%问题解答

    技术2022-07-12  83

    现象

    我写了一段代码来创建一个ini文件,并期望会创建一个General段,里面有我加的两个配置,源码如下:

    #include <QSettings> #include <QDebug> int main(int argc, char *argv[]) { QSettings settings("test.ini", QSettings::IniFormat); settings.beginGroup("General"); settings.setValue("name", "LiMingX"); settings.setValue("age", 19); settings.endGroup(); qDebug() << settings.value("General/name"); return 0; }

    然而运行后效果如下:

    生成的配置文件内容: [%General] name=LiMingX age=19 qDebug输出: QVariant(QString, "LiMingX")

    并没有出现General段,而是%General,但是可以正常读出来。 一般按照正常使用方法,读写ini键需要指定group,但是我指定了group,写入的却不是我期望的.

    原因

    查了半天资料,没有结果,后来找到原因:

    The INI file format has severe restrictions on the syntax of a key. Qt works around this by using % as an escape character in keys. In addition, if you save a top-level setting (a key with no slashes in it, e.g., "someKey"), it will appear in the INI file's "General" section. To avoid overwriting other keys, if you save something using the a key such as "General/someKey", the key will be located in the "%General" section, not in the "General" section.

    大概意思就是:QSettings内置了一个General组用于写特殊信息,如果想自己创建General组,那因为与内置的冲突了,QSettings把自定义的General处理成%General。 从上面的输出可以看出这个处理是透明的,我们可以正常使用General读写,但是打开文件看文件内容就发现我操作的不是General而是%General。

    那该咋办呢?

    解决办法

    办法有2个: 1.读写时不指定group,操作的就是真正的General段

    QSettings settings("test.ini", QSettings::IniFormat); settings.setValue("name", "XiaoHua"); settings.setValue("age", 12); [General] name=XiaoHua age=12

    2.group换个名字,别用General,不会冲突就不会给你改名;

    QSettings settings("test.ini", QSettings::IniFormat); settings.beginGroup("Common"); settings.setValue("name", "XiaoMing"); settings.setValue("age", 11); settings.endGroup(); [Common] name=XiaoMing age=11
    Processed: 0.013, SQL: 9