I am creating an application in pyqt5 to plot multiple figures side by side and above/below each other, and I want to make the plots dockable. The result is not behaving the way I want/would expect and after a long time of searching the internet for answers/solutions I still don't know why.
So far this is my code:
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5 import QtWidgets, QtCore
import traceback
import logging
def exception_hook(exc_type, exc_value, exc_tb):
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
logging.error('\n' + tb)
QtWidgets.QApplication.quit()
class PlotWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(PlotWindow, self).__init__(parent=parent)
self.setWindowTitle('plot window')
self.setCentralWidget(QtWidgets.QWidget(self))
def add_figure(self, figure):
mplCanvas = FigureCanvas(figure)
mplCanvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
dockableMplCanvas = QtWidgets.QDockWidget(self)
dockableMplCanvas.setWidget(mplCanvas)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dockableMplCanvas)
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('matplotlib').setLevel(logging.ERROR)
sys.excepthook = exception_hook
app = QtWidgets.QApplication(sys.argv)
pw = PlotWindow()
for _ in range(4):
fig = Figure(tight_layout=True)
ax = fig.add_subplot()
pw.add_figure(fig)
pw.show()
exit(app.exec_())
It results in the following:
If I now rearrange the plots by first putting one of them on the left of the other three:
..And then putting one underneath the one on the left:
Now if I rescale the window then the space between the two columns of plots expands but the plots don't expand to fill the space:
Why is that? and how can I fix it?
The central widget is resizing to fill the space between the two columns of plots, the solution is to add:
self.centralWidget().setFixedSize(0, 0)
to prevent the central widget from expanding
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.