I am attempting to saving my QGraphicsScene, where the items being drawn may contain references to other items on the scene.
This raises a major concern as when saving to json, and loading from it, the object may appear at correct position but the references is something I am unsure of how to implement.
Is there a way how I can store which object a reference is to? (the referred object is also stored in the json)
I use getstate and setstate methods to serialize my objects, and the ones that will never have references but are always referred are added to the json first so the reference objects are there when loaded.
Here is an MRE:
import json
class shape():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __getstate__(self):
return {
"x": self.x,
"y": self.y,
"width": self.width,
"height": self.height
}
def __setstate__(self, dict):
pass
class line():
def __init__(self, shape1=None, shape2=None):
self.shape1 = shape1
self.shape2 = shape2
def __getstate__(self):
return {
"shape1": self.shape1,
"shape2": self.shape2
}
def __setstate__(self, dict):
self.shape1 = dict['shape1']
self.shape2 = dict['shape2']
if __name__ == "__main__":
shapes = [shape(4, 4 , 4, 4) for _ in range(4)]
line1 = line(shapes[0], shapes[1])
line2 = line(shapes[2], shapes[3])
items = {
"shapes": [item.__getstate__() for item in shapes],
"lines": [line1.__getstate__(), line2.__getstate__()]
}
with open("test.json", "w") as file:
json.dump(items, file)
with open("test.json", "r") as file:
item = json.load(file)
From the above example, i want to retain the line1 and line2 to have references to the specific shapes even after loading.