首页 > 解决方案 > 第二个窗口pyqt5中的matplotlib

问题描述

当在主窗口中单击按钮时,我希望在第二个窗口中绘制 matplotlib 图。使用在主窗口中绘制图形的https://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html,我编写了下面的代码。matplotlib 图形确实是在第二个窗口中绘制的,但它的尺寸非常小,我不明白如何将图形的大小调整到窗口中。我可以帮忙吗?

from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QLabel, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5 import QtCore, QtWidgets
import numpy as np

class MainWindow(QMainWindow):
     def __init__(self):
          super(MainWindow, self).__init__()
          btn = QPushButton('Click me!', self)
          btn.clicked.connect(self.onClick)

     def onClick(self):
          self.SW = SecondWindow()
          self.SW.resize(300,300)
          self.SW.show()

class SecondWindow(QMainWindow):
    def __init__(self):
         super(SecondWindow, self).__init__()
         self.main_widget = QtWidgets.QWidget(self)

         layout = QtWidgets.QVBoxLayout(self.main_widget)
         sc = MyMplCanvas(self.main_widget, width = 300, height = 300)
         layout.addWidget(sc)

class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width= 300, height= 300):
        fig = Figure(figsize=(width, height))
        self.axes = fig.add_subplot(111)

        self.compute_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_figure(self):
        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2*np.pi*t)
        self.axes.plot(t, s)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    MW = MainWindow()
    MW.resize(500, 500)
    MW.show()
    sys.exit(app.exec_())

标签: pythonpython-3.xmatplotlibpyqtpyqt5

解决方案


在您的情况下,main_widget的大小与该大小不同,QMainWindow因此如果您使用它更改大小,self.SW.resize(300,300)则不会更改 self.main_widget 的大小,解决方案是使用布局,但如果QMainWindow这样做不正确因此,由于它具有不应修改的自定义布局:

在此处输入图像描述

在这种情况下的解决方案QMainWindow始终是建立一个中央小部件,在你的情况下它可以使用 self.main_widget:

class SecondWindow(QMainWindow):
    def __init__(self):
         super(SecondWindow, self).__init__()
         self.main_widget = QtWidgets.QWidget()
         self.setCentralWidget(self.main_widget)

         layout = QtWidgets.QVBoxLayout(self.main_widget)
         sc = MyMplCanvas(self.main_widget, width = 300, height = 300)
         layout.addWidget(sc)

推荐阅读