QSettings 比仅使用 dict 有什么优势?

whats the advantage of QSettings over just using a dict?

QSettings在C++中似乎是个很棒的东西,它本质上是一个灵活的散列table,其中键是一个字符串,值是一个QVariant,所以它可以有很多类型。但是,在 Python 中我们已经有了这个,它是一本字典。所以我问,在 PyQt 中使用 QSettings 比只使用 dict 有什么优势?

编辑: 更简洁地说,我使用 QSettings 对象将特定设置分配给特定键的每一行,我都可以用字典做同样的事情。是的,QSettings 有一些优点,比如转换为 ini 文件,但我可以使用相同行数的 json 模块将字典存储到文件中。就 QSettings 提供的能力而言,我试图理解为什么人们会使用它而不是仅仅使用 dict 和 json 模块,例如。我已经仔细阅读了文档以了解 QSettings 提供的功能,没有什么对我来说是一个非常棒的功能,所以我基本上是在问,您认为 QSettings 最有益的功能是什么,为什么它优于使用字典 + json 模块

来自Documentation

Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on macOS and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.

QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports custom storage formats .

QSettings ‘s API is based on QVariant , allowing you to save most value-based types, such as QString , QRect , and QImage , with the minimum of effort.

所以它实际上不仅仅是一个原始的 dict 对象,它处理与在重新启动之间保存应用程序状态相关的常见任务。它实现了许多方便的 methods 来实现这一点。

QSettings is not a container, so in python it is not equivalent to a dictionary. Something similar to a dictionary in Qt/C++ is perhaps QMap(显然有其局限性)。

QSettings 是一个 class,它允许您永久保存信息,也就是说,当应用程序重新打开时,即使是该信息也可以访问,不像字典那样,当应用程序关闭时会丢失它保存的信息。

例如,让我们使用下面的例子运行它几次:

词典:

d = {"foo": "bar"}
print(d)
# modify dictionary
d["foo"] = "rab"

输出:

{'foo': 'bar'}
{'foo': 'bar'}
{'foo': 'bar'}
{'foo': 'bar'}
{'foo': 'bar'}

Q设置:

from PyQt5 import QtCore

settings = QtCore.QSettings("Foo", "Bar")
value = settings.value("value", 0, type=int)
print(value)
settings.setValue("value", value + 1)
settings.sync()

输出:

0
1
2
3
4

在第一种情况下,它不考虑程序的先前执行,但在第二种情况下它考虑。

总而言之,QSettings 允许您保存您的应用程序在再次 运行ning 时可以使用的信息,例如保存会话、权限等

此外,QSettings 是一个抽象层,它在多个平台上实现了之前的功能。


根据您指定的版本,我认为您想将 QSettings 与 dict + json 模块进行比较。

好吧,选择取决于用户,但以下内容可以帮助您选择:

  • QSettings 支持存储许多本机 Qt classes,例如 QSize、QPoint 等。但是 Json 它不支持它们。

所以在所有 QSettings 的最后是一个选项,在 Qt 的世界中是唯一的,但在 Python 的世界中不是唯一的,因为还有其他像 PyYAML(YAML), ConfigParser(INI), xml.etree.ElementTree(XML), 等等