PyQt5 不会将设置保存到 ini 文件

PyQt5 doesn't save settings to ini files

对于应用程序,我需要 read/write .ini 文件中的值。我在 windows7 上使用 python3 和 pyqt5 并得到这个小例子:

import os
from PyQt5.QtCore import QSettings

ini_str = """[mysection]
key0=value0
"""

with open("test.ini", "w") as fi:
    fi.write(ini_str)

inidict = {
    "mysection/key1" : "value1",
    "myothersection/key2" : "value2"
}


settings = QSettings("test.ini", QSettings.IniFormat)

for k in settings.allKeys():
    print(k, settings.value(k))

for k in inidict.keys():
    settings.setValue(k, inidict[k])

从我的 ini 文件中读取值有效,但设置值(如在第二个 for 循环中)无效,值不会保存到 ini 文件中。所以,我想我在这里遗漏了什么?

您必须调用 sync() 方法才能保存值:

...

for k, v in inidict.items():
    settings.setValue(k, v)

settings.sync() # <---

以上在文档中有明确说明:

void QSettings::sync()

Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application.

This function is called automatically from QSettings's destructor and by the event loop at regular intervals, so you normally don't need to call it yourself..

在前面的事情中,它表明此方法负责保持更改,并且如果使用某些 QXXXAplication.exec_() 存在事件循环,则在析构函数中调用它,但在您的情况下没有它,所以你必须明确地调用它。