pythonpyqtqsettings

whats the advantage of QSettings over just using a dict?


QSettings seems like a great thing in C++, it's essentially a flexible hash table where the key is a string and the value is a QVariant, so it can be quite a few types. However, in Python we already have this, its a dictionary. So I ask, what advantage would using QSettings in PyQt have over just using a dict?

Edit: More succinctly, every line that I'd use a QSettings object to assign a particular setting to a particular key, I could do the same thing with a dictionary. Yes, QSettings has some niceties like converting to an ini file but I can store a dict to file with the json module with the same number of lines of code. In terms of faculties provided by QSettings I'm trying to understand why people would use it over just using a dict and the json module, for instance. I've already perused the documentation to understand the things that QSettings offers, nothing stuck out to me as a really great feature so I'm basically asking, what do you view as the most beneficial features of QSettings and why is that superior to using a dict + json module


Solution

  • 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 (obviously with its limitations).

    QSettings is a class that allows you to permanently save information, that is, when the application is reopened then even that information is accessible unlike a dictionary that when the application is closed loses the information it saved.

    For example, let's use the following examples and run it several times:

    Dictionary:

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

    Output:

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

    QSettings:

    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()
    

    Output:

    0
    1
    2
    3
    4
    

    In the first case it does not take into account the previous execution of the program but in the second case it does.

    In conclusion, QSettings allows you to save information that your application can use when running again, such as saving sessions, permissions, etc.

    In addition, QSettings is an abstraction layer that implements the previous functionality on several platforms.


    According to the edition you indicate, I think you want to compare QSettings with dict + json module.

    Well, the choice depends on the user but the following could help you choose:

    So at the end of all QSettings is an option, unique in the world of Qt, but not unique in the world of Python since there are others like PyYAML(YAML), ConfigParser(INI), xml.etree.ElementTree(XML), etc.