Search code examples
pythonpython-3.xpyqtpyqt5qgraphicsscene

How would I duplicate QGraphicsItem's in one function?


How would I duplicate selected items on the scene (self.canvas)?

def use_duplicate(self):
    self.label_btn.setChecked(False)
    self.path_btn.setChecked(False)

    items = self.canvas.selectedItems()
    self.duplicate_stack.append(items)

    for item in items:
        try:
            items = self.duplicate_stack.pop()

            print(self.duplicate_stack)

            self.canvas.addItem(items)

        except Exception as e:
            print(e)

I tried using a list and then grabbing items from the list and adding them to my scene, but this doesn't work. I am curious why there isn't a .clone() method or something along those lines.

Any help is appreciated.


Solution

  • I solved this by copying an item's attributes and creating a new version of itself (QGraphicsTextItem for example):

        def duplicate(self):
            item = CustomTextItem()
            item.setFont(self.font())
            item.setDefaultTextColor(self.defaultTextColor())
            item.setPlainText(self.toPlainText())
            item.setPos(self.pos())
            item.setScale(self.scale())
            item.setRotation(self.rotation())
            item.setZValue(self.zValue())
            item.setTransform(self.transform())
            item.setTransformOriginPoint(self.transformOriginPoint())
    
            item.setFlag(QGraphicsItem.ItemIsSelectable)
            item.setFlag(QGraphicsItem.ItemIsMovable)
            item.setToolTip('Text')
    
            self.scene().addItem(item)
    
            return item