Question

I'm using a QStackedWidget where on Screen 1, I have a QTreeWidget with a list of items and Screen 2 has a few comboboxes and checkboxes. Double clicking on an item in the tree widget takes me to Screen 2. What I want to do is develop a way to remember chosen settings.

So for eg. if I double click on'Item1' in the treewidget, choose some options in the check and combo boxes in screen 2 and return to screen 1 and choose 'Item2' wherein this time I choose a different set of combo items etc. On going back to the first screen again and double clicking on 'Item1', I should restore the options I had previously associated with it.

Hope this makes sense. I needed help on the best way to do this and some code examples would be great.

Really appreciate any help.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top