example of embedding matplotlib in PyQt5

2019-02-20 22:45发布

问题:

Can anybody show a simple example with basic functionality of embedding matplotlib in PyQt5?

There is PyQt4 example available in official docs. PyQt4 will soon be outdated:

Digia have announced that support for Qt v4 will cease at the end of 2015. PyQt5 and Qt v5 are strongly recommended for all new development.

It could be any general example, say, Qt5 QMainWindow/QWidget + matplotlib line plot.

回答1:

what you might be looking for, can be found here: embedded matplotlib in PyQt. It's a blog of one of matplotlib's developers. It is stil written for PyQt4 but it turned out that one just has to change all PyQt4's to 5 and replace QtGui with QtWidtgets. I talked to Ryan and send him the updated code. He was pleased to see that there are people who aknowledge his effort and will updated his tutorial.

Since I had the same problem and was looking around for some solutions to get a start, I found zedcode PyQt5 Introductory Tutorial which doesn't cover matplotlib but can be combined and helps to understand.

Finally, let me say something aobut what one has to do to get matplotlib plots into a Gui. Ryan's tut points out, that one has to build a normal QWidget which will hold the canvas. You can do that with Qt Creator. The part where gui and matplotlib join is the following:

def addmpl(self, fig):
    self.canvas = FigureCanvas(fig)
    self.mplvl.addWidget(self.canvas)
    self.canvas.draw()

mplvl is just the empty QWidget which gets the FigureCanvas and is shown afterwards. For my own app, I wanted to show a 3D-plot, but there are some issues with dropping the mouse support, so there could be some problems left. All 2D plots turned out to be fully functional.

Have a try.

Christian