【问题标题】:how to make pg.PlotItem.removeItem() recognize PlotDataItems solely off name?如何使 pg.PlotItem.removeItem() 仅通过名称识别 PlotDataItems?
【发布时间】:2020-08-27 11:30:51
【问题描述】:

我有一个将 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))
        )

【问题讨论】:

    标签: python pyqt pyqt5 pyqtgraph


    【解决方案1】:

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

    未经测试但应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 2022-11-10
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多