将包含子元素的整个QGraphicScene保存到一个文件中

Save entire QGraphicScene with sub elements to a file

本文关键字:一个 文件 QGraphicScene 包含 元素 保存      更新时间:2023-10-16

我有一个自定义的QGraphicScene,上面有一些QGraphicsItem QGraphicsLine等。与qt的diagramscene示例中显示的方式相同。有没有一种方法可以将它保存到文件中,然后在需要时打开并重复使用或修改它?在PyQt4上工作,但也欢迎使用qt4相关性的答案(c++而不是python)。

这本质上是保存和重新创建。

    ##want to save the scene
    elif key == QtCore.Qt.Key_S and modifier == QtCore.Qt.ControlModifier:
        #saving all the items in the current scene 
        self.arrowItemVec=[]
        self.allItems=self.scene.items()
        #for arrow we need the start and end item to recreate
        #for now only saving the names
        for item in self.allItems:
            if 'Arrow'==item.__class__.__name__:
                self.arrowItemVec.append([item.startItem().name,item.endItem().name])
    elif key == QtCore.Qt.Key_L and modifier == QtCore.Qt.ControlModifier:
        #recreating all the saved items
        #if the scene is cleared before creating new items. we 
        #loose the old item positions
        #essentially we need to save the complete scene
        #detect what item it was and then recreate it 
        newItemVec=[]
        for item in self.allItems:
            if 'DiagramItem'==item.__class__.__name__:
                newItem=DiagramItem(diagramType=item.diagramType,contextMenu=None)
                newItem.name=item.name
                newItem.signaller.showChild.connect(self.showChildGraph)
                newItemVec.append(newItem)
                newItem.setPos(item.pos().x()+10,item.pos().y()+10)               
            #else:
                #print(item.__class__.__name__)
        count=0
        for item in self.allItems:
            if 'Arrow'==item.__class__.__name__:
                for newItem in newItemVec:
                    if newItem.name==self.arrowItemVec[count][0]:
                        startItem=newItem
                    if newItem.name==self.arrowItemVec[count][1]:
                        endItem=newItem
                count+=1
                newArrow=Arrow(startItem,endItem)
                newArrow.setZValue(1000)
                newItemVec.append(newArrow)
        self.scene.clear()
        self.scene.addGrid()
        for item in newItemVec:
            self.scene.addItem(item)

没有直接的方法可以将QGraphicsItem或派生类保存到文件中。

您需要做的是迭代每个项目并保存其属性,然后可以读回这些属性并重新创建场景。

相关文章: