I want to copy or remove a graphic item by right clicking on the item and use the context menu to do it. I have no problem removing the item by using scene().removeItem(self), but i can't make a new copy (or add any kind of graphic item) to the scene by using scene().addItem(). The source code is below, the core problem appears in self_copy function. So what should I do to make a new copy?
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore
from PySide6.QtWidgets import QMenu
class TestLine(pg.InfiniteLine):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.movable = True
def raiseContextMenu(self, ev):
context = QMenu()
context.addAction("remove", self.self_remove)
context.addAction("copy", self.self_copy)
pos = ev.screenPos()
context.exec(QtCore.QPoint(int(pos.x()), int(pos.y())))
def self_copy(self):
self.scene().addItem(self) # It doesn't work.
#self.parentItem().addItem(self) #It doesn't work either.
def self_remove(self):
self.scene().removeItem(self)
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.RightButton:
self.raiseContextMenu(ev)
ev.accept()
app = pg.mkQApp("InfiniteLine Example")
win = pg.GraphicsLayoutWidget(show=True, title="Plotting items examples")
win.resize(1000,600)
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
# Create a plot with some random data
p1 = win.addPlot(title="Plot Items example", y=np.random.normal(size=100, scale=10), pen=0.5)
p1.setYRange(-40, 40)
test = TestLine(pos=(10, 10), angle=45)
p1.addItem(test)
if __name__ == '__main__':
pg.exec()
I also tried self.parentItem().addItem(), but it doens't work either.