python - 第二个窗口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_())
解决方案
在您的情况下,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)
推荐阅读
- php - 想在csv(php)中保存复选框的所有值,不幸的是只有一个被保存
- javascript - amCharts yaxis值格式问题
- haskell - 为 GHCI 重新装箱纯值的目的
- sql - 在 PostgreSQL 中选择/合并用户特定的行和其他后备行
- c# - 迭代扫描期间创建的文件树与通过复制扫描的树创建的文件树之间的时间差
- craftcms - Craft CMS 3 的内部服务器错误
- r - 包含多个变量的箱线图?/ 小提琴情节?
- php - 编写 MySQL 查询以在 PHP 中获取数组组并输出为 JSON
- javascript - 如何在 JavaScript 中生成随机数作为数组的对象
- sql - SQL/Oracle 仅返回第二列中具有相同值的字段