I have a function that adds PlotDataItem to a specific plot widget, however, if I try to use the removeItem function on the plot widget, it doesn't really do anything. I was seeking help on how I can make remove item work for this specific scenario? Any other tips you may recommend for optimization, readability, etc. are also greatly appreciated as I am still fairly new to PyQt and even Python itself. Thank you!
This function includes the removeItem() function.
def updateGraph(self):
"""Clears and updates graph to match the toggled checkboxes.
"""
# self.graphWidget.clear()
for checkboxNumber, checkbox in enumerate(
self.scenarioWidget.findChildren(QtWidgets.QCheckBox)
):
if checkbox.isChecked():
peak = self._model.get_peak(checkboxNumber)
duration = self._model.get_duration(checkboxNumber)
self.drawLine(
name=checkbox.objectName(),
peak=peak,
color=2 * checkboxNumber,
duration=duration,
)
else:
self.graphWidget.removeItem(pg.PlotDataItem(name=checkbox.objectName()))
# TODO: Allow for removal of individual pg.PlotDataItems via self.graphWidget.removeItem()
This function is where the PlotDataItems are added to the plot widget.
def drawLine(self, name, peak, color, duration=100.0):
"""Graphs sinusoidal wave off given 'peak' and 'duration' predictions to model epidemic spread.
Arguments:
name {string} -- Name of scenario/curve
peak {float} -- Predicted peak (%) of epidemic.
color {float} -- Color of line to graph.
Keyword Arguments:
duration {float} -- Predicted duration of epidemic (in days). (default: {100.0})
"""
X = np.arange(duration)
y = peak * np.sin((np.pi / duration) * X)
self.graphWidget.addItem(
pg.PlotDataItem(X, y, name=name, pen=pg.mkPen(width=3, color=color))
)
You're creating a new object with pg.PlotDataItem(name=checkbox.objectName())
, so it will not be found as it's completely new.
Untested but should work:
for item in self.graphWidget.listDataItems():
if item.name() == checkbox.objectName():
self.graphWidget.removeItem(item)