我正在尝试学习matplotlib,并尝试测试以下代码。
import matplotlib
from matplotlib.figure import Figure
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import sys
from PySide2 import QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
wid = QtGui.QWidget()
wid.resize(250, 150)
grid = QtGui.QGridLayout()
wid.setLayout(grid)
fig = Figure(figsize=(7,5), dpi=65, facecolor=(1,1,1), edgecolor=(0,0,0))
canvas = FigureCanvas(fig)
grid.addWidget(canvas)
wid.show()
但是似乎无法识别Figure的签名。
TypeError:“ PySide2.QtGui.QGridLayout.addWidget”调用错误 参数类型:
支持PySide2.QtGui.QGridLayout.addWidget(FigureCanvasQTAgg) 签名:
PySide2.QtGui.QGridLayout.addWidget(PySide2.QtGui.QWidget,int,int, PySide2.QtCore.Qt.Alignment = 0)
PySide2.QtGui.QGridLayout.addWidget(PySide2.QtGui.QWidget,int,int, int,int,PySide2.QtCore.Qt.Alignment = 0)
答案 0 :(得分:2)
PySide2是Qt5的绑定,因此您必须使用backend_qt5agg
而不是backend_qt4agg
,另一方面,建议在matplotlib之前导入后端(在这种情况下为PySide2),以便matplotlib对其进行配置在内部,除了QApplication之外,QWidget和QGridLayout都属于QtWidgets,因为Qt5将它们与QtGui分开了,最后,当您向QGridLayout添加小部件时,必须在以下参数中指明其位置。
考虑到以上解决方案是
import sys
from PySide2 import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
wid = QtWidgets.QWidget()
wid.resize(250, 150)
grid = QtWidgets.QGridLayout(wid)
fig = Figure(figsize=(7, 5), dpi=65, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
canvas = FigureCanvas(fig)
grid.addWidget(canvas, 0, 0)
wid.show()
sys.exit(app.exec_())