简体   繁体   中英

How can I show matplotlib on my PyQt5 Qwidget

I want to draw on my PyQt designer file. I made 2 py file, one is Main, and another one is ui file(pyuic) this is code of UI

self.graph_widget = QtWidgets.QWidget(self.tab_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.graph_widget.sizePolicy().hasHeightForWidth())
self.graph_widget.setSizePolicy(sizePolicy)
self.graph_widget.setObjectName("graph_widget")

graph_widget is widget name

    def show_graph(self):

        self.graph_widget.fig = plt.Figure()
        self.graph_widget.canvas = FigureCanvas(self.graph_widget.fig)

        canvasLayout = QVBoxLayout()
        canvasLayout.addStretch(1)

        self.graph_widget.layout = QHBoxLayout()
        self.graph_widget.layout.addLayout(canvasLayout)

        ax = self.graph_widget.fig.add_subplot(1, 1, 1) 
        ax.grid()
        self.graph_widget.canvas.draw() 

This is code of Main for show graph on my widget. I want to show graph on my widget, but it doesn't work. just show white window as before send signal. and doesn't print any error.

please let me know how I print it.

I think you don't understand well the concept of objects. In your function show_graph(), you wrote self.graph_widget.fig, that means, fig is an attribute (a variable) of the object graph_widget, which is an object QWidget, so by writing self.graph_widget.fig = plt.Figure() has no sense. I suggest you this solution:

def show_graph(self):
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas #You can put it at the beginning of your program
    self.fig = plt.Figure()
    self.plot = self.fig.add_subplot()
    self.canvas = FigureCanvas(self.fig)
    self.canvas.draw()
    #Create a layout
    layout = QVBoxLayout()
    layout.addWidget(self.canvas)
    #You can now add your layout to your QWidget()
    self.graph_widget.setLayout(layout)
    #You can active the grid by the following line
    self.plot.yaxis.grid()

Sorry for my English, I am French.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM