移动到 QGraphicsView 时创建没有 window 打开和关闭的 pyqtgraph 图

Create pyqtgraph plot without window opening and closing when moved to QGraphicsView

我正在尝试为 Pyqt 应用程序创建一个折线图,该图本身工作正常但我很恼火的是它打开 window 瞬间然后关闭和情节移动到 Qt QGraphicsView。我已经搜索了解决方案,但似乎找不到任何有效的答案。

def lineChartTest(self):
    x = np.array(list(range(0, 10)))
    y = np.array([3, 7, 5, 11, 8, 13, 9, 16, 15, 12])
    x_smooth = np.linspace(x.min(), x.max(), 300)
    spl = make_interp_spline(x, y, k=3)
    y_smooth = spl(x_smooth)

    plot = pg.plot()
    plot.setGeometry(0, 0, 1007, 500)
    plot.setLabel('bottom', 'X-axis Values')
    plot.setLabel('left', 'Y-axis Values')
    plot.setXRange(0, 10)
    plot.setYRange(0, 20)
    plot.setTitle("Test pyqtgraph")
    plot.setBackground('1E1B44')
    line = plot.plot(x_smooth, y_smooth, pen=pg.mkPen('E42AFF', width=2))
    plot.addLegend()

    self.scene.addWidget(plot)

这是我目前用来创建绘图的代码。

plot() 函数在返回之前自动 显示 PlotWidget(参见 sources),因此它被短暂显示为顶层 window 在添加到视图之前。

由于您没有向 plot() 添加任何参数,因此您实际上并不需要该函数,您只需创建一个新的 PlotWidget 实例并将其添加到视图即可:

    def lineChartTest(self):
        # ...
        plot = pg.PlotWidget()
        # ...

另一方面,PlotWidget 已经 是 QGraphicsView,因此将视图添加到另一个场景中可能没有多大意义。考虑使用 PlotWidget 而不是 QGraphicsView,并向其添加 PlotItems。