How can I find an open pyqtgraph GraphicsWindow similar to how 'matplotlib.pyplot.gcf()` works?
我会像一个
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
这可以通过
这是因为python缓存导入模块的方式,所以再次导入
例如:制作
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() |
然后是
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() |
最后,我们可以实现
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() |
然后用
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 |
子类化