-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonMPL.py
More file actions
82 lines (59 loc) · 2.58 KB
/
Copy pathCommonMPL.py
File metadata and controls
82 lines (59 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
"""A TraitsUI editor that embeds a matplotlib figure in a Qt5 application.
Originally a Qt adaptation by Pierre Haessig (March 2014) of Gael Varoquaux's
tutorial on integrating matplotlib with TraitsUI, based on Qt code shared by
Didrik Pinte (May 2012):
* https://docs.enthought.com/traitsui/tutorials/traits_ui_scientific_app.html
* https://gist.github.com/pierre-haessig/9838326
Import order matters here. ``pyface.qt`` is imported first so that it resolves
and caches the Qt binding (PyQt5, PySide2, ...); matplotlib then reuses the
already-imported binding instead of independently picking a different one,
which would crash the moment the two tried to share a widget.
"""
# isort: off
# Order is deliberate -- see the module docstring. pyface.qt must resolve the
# Qt binding before matplotlib looks for one. Do not let a formatter sort these.
from pyface.qt import QtGui
from matplotlib.backends.backend_qtagg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar,
)
# isort: on
from traitsui.api import Handler
from traitsui.basic_editor_factory import BasicEditorFactory
from traitsui.qt.editor import Editor
__all__ = ["MPLFigureEditor", "MPLInitHandler"]
class _MPLFigureEditor(Editor):
"""Wraps a :class:`~matplotlib.figure.Figure` trait in a Qt canvas."""
scrollable = True
def init(self, parent):
self._canvas = None
self.control = self._create_canvas(parent)
self.set_tooltip()
def update_editor(self):
"""Redraw the canvas when the underlying figure trait changes."""
if self._canvas is not None:
self._canvas.draw_idle()
def _create_canvas(self, parent):
"""Build a frame holding the MPL canvas and its navigation toolbar."""
frame = QtGui.QWidget()
mpl_canvas = FigureCanvas(self.value)
mpl_canvas.setParent(frame)
self._canvas = mpl_canvas
mpl_toolbar = NavigationToolbar(mpl_canvas, frame)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(mpl_canvas)
vbox.addWidget(mpl_toolbar)
frame.setLayout(vbox)
return frame
class MPLFigureEditor(BasicEditorFactory):
"""Editor factory: ``Item('figure', editor=MPLFigureEditor())``."""
klass = _MPLFigureEditor
class MPLInitHandler(Handler):
"""Calls ``mpl_setup()`` on the view object once its controls exist.
Attach this to a ``View`` when you need to register matplotlib event
handlers (pickers, selectors) that require a live canvas.
"""
def init(self, info):
info.object.mpl_setup()
return True