2

I have been following this chapter to embed a matplotlib Figure into a QTdesigner generated GUI. So far it works, but I need to also embed the toolbar within the GUI to manipulate the plot and save it. How can I modify the example code to add the toolbar? I have googled many sources and they all have their own custom code that does not work with the example given in the book.

I believe I need to modify the custom widget class. The code for the widget class is here:

Original code (from book):

from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    def __init__(self):
        self.fig = Figure()       
        self.ax = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
        QtGui.QSizePolicy.Expanding,
        QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class MplWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.canvas = MplCanvas()      
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.canvas)     
        self.setLayout(self.vbl)

My question is how can I add code such that the toolbar will display with the canvas?

I know I must import the api using:

from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar

Do I need to create a new class and/or custom widget to put it in?

2
  • Ok, after more fiddling around and looking at link, I modified the class MplWidget to: class MplWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.canvas = MplCanvas() self.mpl_toolbar = NavigationToolbar(self.canvas, self) self.vbl = QtGui.QVBoxLayout() self.vbl.addWidget(self.canvas) self.vbl.addWidget(self.mpl_toolbar) self.setLayout(self.vbl) And now it works. Thanks! Commented Aug 30, 2013 at 19:04
  • 1
    Please post that comment as an answer and accept it. Commented Aug 30, 2013 at 19:15

1 Answer 1

2

Ok, after more fiddling around and looking at link, I modified the class MplWidget to:

class MplWidget(QtGui.QWidget):
     def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.canvas = MplCanvas()
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.canvas)
        self.vbl.addWidget(self.mpl_toolbar)
        self.setLayout(self.vbl)

And now it works. Thanks!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.