I got some time to sit down and work this out – and it was a littl trickier than I was expecting. As I mentioned above, you can promote widgets in Qt Designer, and in theory all that should be needed is to promote a widget to a
FigureCanvasQTAgg using the correct import path for the header file.
Unfortunately, this doesn’t work – all of the matplotlib “widget” classes expect a figure object as their first parameter while Qt expects the first parameter to be parent, and passes this in regardless. This doesn’t work.
The solution is to create our own custom “widget” which wraps the
FigureCanvasQTAgg accepting the parent value and then creates the figure/etc. itself. This will allow this class to be created automatically by Qt from the ui file.
In a file named
canvas.py in the root of my project, I added the following –
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
def __init__(self, parent=None):
# self.setParent(parent) optional
fig = Figure(figsize=(5, 5))
Now in Qt designer we can use this custom widget as our promote target, eg.
A custom UI was created as a single
QWidget added to a main window, which was then promoted to a
The QWidget is promoted by right-clicking on it and choosing promote.
The Promoted class name is “MplCanvas” and header file is “canvas” (no extension) and we’re using
QWidget as the base class.
Saving this file as
mainwindow.ui we can then load the working plot UI with the following code. This is a very basic example, but you can use these widgets just like any other in your applications. The “canvas” has a
figure property to which you can add subplots, etc.
from PyQt5 import QtWidgets, uic
app = QtWidgets.QApplication(sys.argv)
window = uic.loadUi("mainwindow.ui")
axes = window.canvas.figure.add_subplot(1,1,1)
Which produces the following window…
Hope that helps? Let me know if you have any questions.