简体   繁体   English

在PyQt5中嵌入Matplotlib:工具栏不起作用

[英]Embedding Matplotlib in PyQt5: Toolbar doesn't work

I'm developing an application for image-manipulation using matplotlib and pyqt5. 我正在开发一个使用matplotlib和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: 现在,如果我加载图像并将其绘制到画布上,则会出现两个问题:

  1. The toolbar will be shown, but it has no effect (eg zoom, pan, etc.) 将显示工具栏,但没有任何作用(例如,缩放,平移等)
  2. 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 figimage is directly placed onto the canvas without axes. figimage直接放置在画布上,而无需使用轴。 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. 您可以使用figimage的resize参数self.figure.figimage(img, resize=True)使画布适合图像。 Otherwise, you'd probably want to use an imshow plot. 否则,您可能需要使用imshow图。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM