Hello list,

A couple months ago, I spent quite a bit of time trying to figure out how
to use Qt designer create a GUI with an embedded MPL window. Unfortunately,
the Scipy cookbook page (
http://wiki.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer) is
very outdated. A recent post (
http://matplotlib.1069221.n5.nabble.com/Re-Keep-list-of-figures-or-plots-and-flip-through-list-using-UI-td44961.html)
brought up some questions about a use case very similar to mine, so I redid
my example and was going to write a quick tutorial for the docs.

Unfortunately, I'm not a Qt guru, so I thought that I would ask on the list
for some advice.  The OP and I were both interested in being able to have a
list of figures that you could select from to change the plot window. The
embedding examples in the docs create subclasses of FigureClass* and embed
the plotting figure/axes/etc. This works but gets tricky, though, when
trying to switch plots. Also, for interactive IPython work, I didn't like
that the plotting objects were mixed in with all the QtGui.QWidget
attributes, which makes introspective searching painful. My solution was to
create a dictionary of matplotlib.figure.Figure objects that had all of the
plotting stuff defined. Then when I select a new plot from the list, the
old one is removed and a new FigureClass object is created using the
selected Figure object. Has anyone else successfully done something like
this? Is there a better way? Also, it seems if I zoom the current plot,
change to a new plot, and change back, the zoom region is retained. Anyone
know how to reset the zoom region?

Attached is my example: "window.py" is the Designer-created main window and
"custommpl.py" is the subclass of the main window that I wrote. It's about
as short as I could make it.

Thanks

Ryan
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test2.ui'
#
# Created: Wed Feb 18 18:20:27 2015
#      by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.mplfigs = QtGui.QListWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mplfigs.sizePolicy().hasHeightForWidth())
        self.mplfigs.setSizePolicy(sizePolicy)
        self.mplfigs.setMaximumSize(QtCore.QSize(200, 16777215))
        self.mplfigs.setObjectName(_fromUtf8("mplfigs"))
        self.gridLayout.addWidget(self.mplfigs, 0, 1, 1, 1)
        self.mplwindow = QtGui.QWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mplwindow.sizePolicy().hasHeightForWidth())
        self.mplwindow.setSizePolicy(sizePolicy)
        self.mplwindow.setObjectName(_fromUtf8("mplwindow"))
        self.gridLayout.addWidget(self.mplwindow, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

import sys

from PyQt4 import QtGui

import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar)

from window import Ui_MainWindow

        
class Main(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)
        self.mplvl = QtGui.QVBoxLayout(self.mplwindow)
        self.mplfigs.itemClicked.connect(self.changefig)
        fig = Figure()
        self.addmpl(fig)

    def addfigs(self, fig_dict):
        self.fig_dict = fig_dict
        names = list(fig_dict.keys())
        self.mplfigs.addItems(names)

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, 
                self, coordinates=True)
        self.mplvl.addWidget(self.toolbar)
        #self.addToolBar(self.toolbar)

    def rmmpl(self,):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def changefig(self, item):
        text = item.text()
        self.rmmpl()
        self.addmpl(self.fig_dict[text])


if __name__ == '__main__':
    figs = {}
    fig1 = Figure()
    ax1f1 = fig1.add_subplot(111)
    ax1f1.plot(np.random.rand(5))
    figs['One Plot'] = fig1

    fig2 = Figure()
    ax1f2 = fig2.add_subplot(121)
    ax1f2.plot(np.random.rand(5))
    ax2f2 = fig2.add_subplot(122)
    ax2f2.plot(np.random.rand(10))
    figs['Two Plots'] = fig2

    app = QtGui.QApplication([])
    main = Main()
    main.addfigs(figs)
    main.show()
    sys.exit(app.exec_())

------------------------------------------------------------------------------
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration & more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=190641631&iu=/4140/ostg.clktrk
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Reply via email to