I wish to plot a matplotlib graph in a second window when a button is clicked in the main window. Using https://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html , which plots a graph in the main window, I wrote the code below. The matplotlib graph is indeed plotted in a second window, but it has a very small size and I don't understand how to adjust the size of the graph to the window. May I have some help?
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_())
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…