我正在构建一个PyQt应用程序,我对python很初学。假设我将obj项存储在已定义的类中:
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
然后我通过GUI执行其他操作并创建一个Items列表。如何保存此列表以便以后可以打开它? pickle不适用于QPixmap,我想保存一个。
答案 0 :(得分:1)
您可以使用QSettings保存所有应用程序数据。它会自动转换QPixmap
,QPoint
,QColor
等数据类型。默认情况下,设置会保存在platform-independant way中,但您也可以保存为自定义如果你想要的话。
以下是阅读/编写Item
课程的方法:
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()
QSettings.value()
的PyQt版本允许您指定默认值和值的预期类型。