matplotlib 如何在pyqt布局中添加FigureCanvasQTAgg?

ve7v8dk2  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(186)

当我将matplotlib图形添加到pyqt5环境中时,我遇到了一个问题。
我得到这个错误:

File "C:\Users\maxime\Desktop\SESAME\PycharmProjects\neocom\di.py", line 37, in __init__
    layout.addWidget(self.canvas)
TypeError: addWidget(self, a0: QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()): argument 1 has unexpected type 'FigureCanvasQTAgg'

字符串
我不明白这个错误,因为我看到的每一篇文章都做了同样的事情来添加这个数字。我哪里做错了?这就像FigureCanvasQTAgg不是一个小部件,但它应该是,对吗?

from PyQt5.QtGui import *
from PyQt5.QtWidgets import  *
from PyQt5.QtCore import *
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

class window(QMainWindow):
    def __init__(self, parent=None):
        super(window, self).__init__()
        self.parent = parent
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.mainHBOX_param_scene = QHBoxLayout()
        V1 = Viewer()
 
        self.mainHBOX_param_scene.addWidget(V1)
        self.centralWidget.setLayout(self.mainHBOX_param_scene)

class Viewer(QGraphicsView):
    def __init__(self, parent=None):
        super( Viewer, self).__init__(parent)
        self.parent = parent
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        self.axes_Delay = self.figure.add_subplot(1, 1,1)
        self.axes_Delay.set_title("Title")

        # self.canvas.setGeometry(0, 0, 1600, 500 )
        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        self.canvas.show()
 
def main():
    app = QApplication(sys.argv)
    ex = window(app)
    ex.show()
    sys.exit(app.exec_( ))

if __name__ == '__main__':
    main()

bjp0bcyl

bjp0bcyl1#

我在PyQt 6和MatPlotLib之间的集成中遇到了同样的问题,直到我发现了这个新命令:

matplotlib.use('Qt5Agg')

字符串
紧接着:

import matplotlib.pyplot as plt


而且,我发现最好有:

from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas


而不是:

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas


对我来说,你的代码似乎没有什么问题,似乎只是一个错误,由于不同的版本和MatPlotLib和PyQt之间的集成(与PyQt 6没有办法使它工作,至少对我来说)。在matplotlib.use()中的默认配置在文档(https://matplotlib.org/stable/users/explain/backends.html)中并不是很清楚。
希望这对你有帮助!

相关问题