Matplotlib and PySide

  • Hello,

    I'm trying to embed a matplotlib figure within QMainWindow using pyside. In the following example a rectangle is plotted and now I want to have it draggable by using mouse-commands. Why is the following code not working? If I use the DraggableRectangle-Class without Qt it works quite well.

    @import numpy as np
    import matplotlib.pyplot as plt
    import sys

    from PySide import QtCore, QtGui
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

    class DraggableRectangle:
    def init(self, rect):
    self.rect = rect = None

    def connect(self):
        'connect to all the events we need'
        self.cidpress = self.rect.figure.canvas.mpl_connect(
            'button_press_event', self.on_press)
        self.cidrelease = self.rect.figure.canvas.mpl_connect(
            'button_release_event', self.on_release)
        self.cidmotion = self.rect.figure.canvas.mpl_connect(
            'motion_notify_event', self.on_motion)
    def on_press(self, event):
        'on button press we will see if the mouse is over us and store some data'
        if event.inaxes != self.rect.axes: return
        contains, attrd = self.rect.contains(event)
        if not contains: return
        print 'event contains', self.rect.xy
        x0, y0 = self.rect.xy = x0, y0, event.xdata, event.ydata
    def on_motion(self, event):
        'on motion we will move the rect if the mouse is over us'
        if is None: return
        if event.inaxes != self.rect.axes: return
        x0, y0, xpress, ypress =
        dx = event.xdata - xpress
        dy = event.ydata - ypress
        #print 'x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f'%(x0, xpress, event.xdata, dx, x0+dx)
    def on_release(self, event):
        'on release we reset the press data' = None
    def disconnect(self):
        'disconnect all the stored connection ids'

    class MainWindow(QtGui.QMainWindow):
    def init(self, parent=None):
    super(MainWindow, self).init(parent)

        self.setGeometry(100, 100, 1000, 600)
        self.fig = plt.Figure((16, 4))
        self.fig.subplots_adjust(0.01, 0.01, 0.99, 0.99)
        self.canvas = FigureCanvas(self.fig)
        self.subplot = self.fig.add_subplot(111)
        self.subplot.set_axis_off() = None
        self.rect = plt.Rectangle((0.5,0.5), 0.3, 0.3, edgecolor='r', facecolor='green', picker=10)
        dr = DraggableRectangle(self.rect)

    def main():
    app = QtGui.QApplication(sys.argv)
    form = MainWindow()


    Thank you for your help in advance!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.