All tree-widget items have a setData method that you can use to store associated values, which in this case would just be a dict
containing the settings.
To make saving and restoring the settings easier, it would be advisable to make sure all the checkboxes, comboboxes, etc have a common parent, and that they are all given a unique objectName
. That way, it will make it easy to iterate over them:
def saveSettings(self):
settings = {}
for child in self.settingsParent.children():
name = child.objectName()
if not name:
continue
if isinstance(child, QtGui.QCheckBox):
settings[name] = child.isChecked()
elif isinstance(child, QtGui.QComboBox):
settings[name] = child.currentIndex()
...
return settings
def restoreSettings(self, settings):
for child in self.settingsParent.children():
name = child.objectName()
if name not in settings:
continue
if isinstance(child, QtGui.QCheckBox):
child.setChecked(settings[name])
elif isinstance(child, QtGui.QComboBox):
child.setCurrentIndex(settings[name])
...
To add the settings to the tree-widget item, you just need to do something like this:
settings = self.saveSettings()
item.setData(0, QtCore.Qt.UserRole, settings)
and to retrieve them, do this:
settings = item.data(0, QtCore.Qt.UserRole)
self.restoreSettings(settings)
But note that you may need to take an extra step here if you are using python2, because data
will return a QVariant
, rather than a dict
. If that is the case, to get the dict
, you will need to do this instead:
settings = item.data(0, Qt.QtCore.Qt.UserRole).toPyObject()
Alternatively, you can get rid of QVariant
everywhere but putting this at the beginning of your program:
import sip
sip.setapi('QVariant', 2)
from PyQt4 import ... etc