关于python:如何找到一个类似于’matplotlib.pyplot.gcf()`的开放式pyqtgraph GraphicsWindow?

How can I find an open pyqtgraph GraphicsWindow similar to how 'matplotlib.pyplot.gcf()` works?

我会像一个pyqtgraph配套matplotlib.pyplot.gcf()函数,它返回一个数字参考电流。我想这是一个函数返回一个参考电流pyqtgraphGraphicsWindow实例。有没有办法这样做吗?


PyqTgraph中没有隐含的"当前图形"概念;应该显式引用每个窗口或图形对象。例如:

1
2
3
4
5
6
7
plot_window = pg.plot()

# Add data to this plot:
plot_curve = plot_window.plot(data)

# Update data in this curve:
plot_curve.setData(data)

如果您只想获取当前活动的窗口,那么qt可以提供:http://doc.qt.io/qt-5/qapplication.html active window


这可以通过

  • 创建跟踪窗口的全局列表
  • pg.GraphicsWindowpg.PlogWidget的子类
  • 向全局跟踪列表添加新创建的子类窗口/小部件实例
  • 覆盖closeEvent,因此当窗口关闭时,它会从跟踪器中删除窗口。
  • 这是因为python缓存导入模块的方式,所以再次导入tracking.tracker应该访问相同的变量。

    例如:制作tracking.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import warnings


    class WTracker:

        def __init__(self):
            self.open_windows = []

        def window_closed(self, win):
            if win in self.open_windows:
                self.open_windows.remove(win)
            else:
                warnings.warn('  tracker received notification of closing of untracked window!')

        def window_opened(self, win):
            self.open_windows += [win]


    tracker = WTracker()

    然后是figure.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import pyqtgraph as pg
    from tracking import tracker


    class Figure(pg.GraphicsWindow):
        def __init__(self):
            super(Figure, self).__init__()
            tracker.window_opened(self)

        def closeEvent(self, event):
            tracker.window_closed(self)
            event.accept()

    最后,我们可以实现gcf();我们把它放到pyplot.py中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from tracking import tracker
    from figure import Figure


    def gcf():
        if len(tracker.open_windows):
            return tracker.open_windows[-1]
        else:
            return Figure()

    然后用tester.py进行试验:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import sys
    from PyQt4 import QtGui
    from figure import Figure
    from pyplot import gcf

    app = QtGui.QApplication(sys.argv)

    fig1 = gcf()
    fig2 = gcf()
    fig3 = Figure()
    fig4 = gcf()
    fig4.close()
    fig5 = gcf()

    print('fig2 is fig1 = {}'.format(fig2 is fig1))
    print('fig3 is fig1 = {}'.format(fig3 is fig1))
    print('fig4 is fig3 = {}'.format(fig4 is fig3))
    print('fig5 is fig3 = {}'.format(fig5 is fig3))
    print('fig5 is fig1 = {}'.format(fig5 is fig1))

    结果:

    1
    2
    3
    4
    5
    6
    $ python tester.py
    fig2 is fig1 = True
    fig3 is fig1 = False
    fig4 is fig3 = True
    fig5 is fig3 = False
    fig5 is fig1 = True

    子类化pg.PlotWidget而不是pg.GraphicsWindow的工作,但是您必须创建一个布局,将其设置为中心项,然后运行self.show()