Saving class data containing pyqt objects

834 views Asked by At

I'm building a PyQt app and I'm quite beginner with python. Let's say I store an obj item in a defined class:

class Item (self):
    def __init__(self, item_nbr, crop_pixmap, originepoint, designation):
        self.item_nbr = item_nbr            # integer
        self.crop_pixmap = crop_pixmap      # QPixmap
        self.origin_point = originpoint     # QPoint
        self.designation = designation      # str

Then I work through a GUI perform other operation and create a list of Items. How can I save this list so that I can open it later ? pickle does not work with QPixmap and I'd like to save a single.

1

There are 1 answers

1
ekhumoro On BEST ANSWER

You can use QSettings to save all your application data. It will automatically convert data types like QPixmap, QPoint, QColor, etc. By default, the settings are saved in a platform-independant way, but you can also save to a custom location if you want.

Here is how you could read/write your Item class:

def settings(self):
    # use a custom location
    return QtCore.QSettings('app.conf', QtCore.QSettings.IniFormat)

def readSettings(self):
    self.items = []
    settings = self.settings()
    for index in range(settings.beginReadArray('items')):
        settings.setArrayIndex(index)
        self.items.append(Item(
            settings.value('number', -1, int),
            settings.value('pixmap', None, QtGui.QPixmap),
            settings.value('point', None, QtCore.QPoint),
            settings.value('designation', '', str),
            ))

def writeSettings(self):
    settings = self.settings()
    settings.beginWriteArray('items')
    for index, item in enumerate(self.items):
        settings.setArrayIndex(index)
        settings.setValue('number', item.item_nbr)
        settings.setValue('pixmap', item.crop_pixmap)
        settings.setValue('point', item.origin_point)
        settings.setValue('designation', item.designation)
    settings.endArray()

The PyQt version of QSettings.value() allows you to specify both a default value and the expected type of the value.