如何使 pg.PlotItem.removeItem() 仅根据名称识别 PlotDataItems?

how to make pg.PlotItem.removeItem() recognize PlotDataItems solely off name?

我有一个函数可以将 PlotDataItem 添加到特定的绘图小部件,但是,如果我尝试在绘图小部件上使用 removeItem 函数,它实际上并没有做任何事情。我正在寻求帮助,了解如何让删除项目适用于这种特定情况?您可能推荐的关于优化、可读性等的任何其他技巧也非常感谢,因为我对 PyQt 甚至 Python 本身还是相当陌生。谢谢!

此函数包含 removeItem() 函数。

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()

此函数是将 PlotDataItems 添加到绘图小部件的地方。

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))
        )

您正在使用 pg.PlotDataItem(name=checkbox.objectName()) 创建一个新对象,因此不会被发现,因为它是全新的。

未经测试但应该有效:

for item in self.graphWidget.listDataItems():
    if item.name() == checkbox.objectName():
        self.graphWidget.removeItem(item)