Python – Is it possible to pickle QSettings objects?

Is it possible to pickle QSettings objects?… here is a solution to the problem.

Is it possible to pickle QSettings objects?

I realize this sounds very redundant because pickle and QSettings basically serve the same purpose, but let me explain.

I have a program consisting of widgets that can be docked, resized, or otherwise modified. Users want to be able to save various states as layouts and change between those layouts. The layout is saved as a QSettings file.

To save the list of layouts, I want to pickle a dictionary in the format {'layoutName':qSettingsFile, 'anotherName':anotherFile}, but when I try the pickle QSettings file, I get TypeError:sip.wrapper type cannot be instantiated or subclassed

Is there a way to get it to work? I could put the contents of the QSettings file into a dictionary and forget about QSettings, but I wish there was an easier/shorter way.

Solution

Use a settings file and create separate groups for each layout.

QSettings syntax supports hierarchical keys, so just use it beginGroup and endGroup creates a named layout part:

settings.beginGroup('layouts')
settings.beginGroup('layoutname1')
# set various layout values...
settings.endGroup()
settings.beginGroup('layoutname2')
# set various layout values...
settings.endGroup()
settings.endGroup()

This will output a file similar to the following:

layouts/layoutname1/value1=true
layouts/layoutname1/value2=true
...
layouts/layoutname2/value1=false
layouts/layoutname2/value2=false
...

Alternatively, you can create an indexed list of layouts using QSettings arrays.

Related Problems and Solutions