Q:

Embedding Matplotlib in PyQt5: Toolbar doesn't work

I'm developing an application for image-manipulation using matplotlib and pyqt5. Here's some code:
class MainForm(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainForm, self).__init__()
        uic.loadUi("...", self)

        self.setup_ui_elements()

        self.figure = Figure(figsize=(5, 4), dpi=100)

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NaviToolbar(self.canvas, self)

        self.MiddleRightLayout.addWidget(self.toolbar)
        self.MiddleRightLayout.addWidget(self.canvas)

    def plot(self, img):
        self.figure.figimage(img)
        self.canvas.draw()

Now if I load an image and plot it to the canvas, two problems arise:

The toolbar will be shown, but it has no effect (e.g. zoom, pan, etc.)
I haven't found a way to fit the image to the canvas, the image is usually much bigger as the canvas-area.

Any ideas?
greets, dennis

A:

A figimage is directly placed onto the canvas without axes. This means it does not automatically scale to the canvas or anything else and it also means that the zoom and pan tools do not have any effect. 
You may use the resize argument to figimage, self.figure.figimage(img, resize=True) to let the canvas fit to the image, if that is what you want. Otherwise, you'd probably want to use an imshow plot.
In order to get the image scaled to its original size, you need to work a bit on the spacings. 
import matplotlib.pyplot as plt
import numpy as np 

def plot(self, img):
    self.ax = self.figure.add_subplot(111)
    self.figure.subplots_adjust(.1,.1,.9,.9) # 10% margin around image
    h, w = np.array(img.shape[:2])/self.figure.dpi
    self.figure.set_size_inches(w/0.8,h/0.8)
    self.ax.imshow(img)
    self.ax.axis("off") # in case you want to turn the axes off
    self.canvas.draw()

