traitsui matplotlib editor with toolbar using qt backend

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

traitsui matplotlib editor with toolbar using qt backend

Ryan Olf
I was unable to find any notes on using the mpl toolbar with a qt-based traitsui mpl editor. I put together this class, which seems to work, so I'm putting it out on the email list so others in my situation can find a possible solution easily. The example included also uses an mpl widget and event handling. It would be nice to see more examples of how to use matplotlib with traitsui with the official docs.



from pyface.qt import QtGui, QtCore
from traits.etsconfig.api import ETSConfig
ETSConfig.toolkit = 'qt4'

import matplotlib as mpl

# We want matplotlib to use a QT backend
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg

from enthought.traits.api import Any, Instance
from enthought.traits.ui.qt4.editor import Editor
from enthought.traits.ui.qt4.basic_editor_factory import BasicEditorFactory
from traitsui.api import Handler

class _MPLFigureEditor(Editor):

   scrollable  = True

   def init(self, parent):
       self.control = self._create_canvas(parent)

   def update_editor(self):

   def _create_canvas(self, parent):
       """ Create the MPL canvas. """
       # matplotlib commands to create a canvas
       frame = QtGui.QWidget()
       mpl_canvas = FigureCanvas(self.value)
       mpl_toolbar = NavigationToolbar2QTAgg(mpl_canvas,frame)

       vbox = QtGui.QVBoxLayout()

       return frame

class MPLFigureEditor(BasicEditorFactory):

   klass = _MPLFigureEditor

class MPLInitHandler(Handler):
    """Handler calls mpl_setup() to initialize mpl events"""
    def init(self, info):
        """This method gets called after the controls have all been
        created but before they are displayed.
        return True

if __name__ == "__main__":
    # Create a window to demo the editor
    from enthought.traits.api import HasTraits
    from enthought.traits.ui.api import View, Item
    from numpy import sin, cos, linspace, pi
    from matplotlib.widgets import  RectangleSelector

    class Test(HasTraits):

        figure = Instance(Figure, ())

        view = View(Item('figure', editor=MPLFigureEditor(),

        def __init__(self):
            super(Test, self).__init__()
            self.axes = self.figure.add_subplot(111)
            t = linspace(0, 2*pi, 200)
            self.axes.plot(sin(t)*(1+0.5*cos(11*t)), cos(t)*(1+0.5*cos(11*t)))

        def mpl_setup(self):
            def onselect(eclick, erelease):
                print "eclick: {}, erelease: {}".format(eclick,erelease)
   = RectangleSelector(self.axes, onselect,


Enthought-Dev mailing list
[hidden email]