Show multiple graphs in scrollable widgets with PyQt and matplotlib

Since I did not receive an answer to this question, I tried to solve it with PyQt. Apparently, this is not so easy when QScrollArea is involved ...

I wrote a small test that basically does what I'm looking for, but it does not show the scroll area and the sections inside it, as I expected:

from PyQt4 import QtCore, QtGui import os,sys #import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure qapp = QtGui.QApplication(sys.argv) qwidget = QtGui.QWidget() qwidget.setGeometry(QtCore.QRect(0, 0, 500, 500)) qlayout = QtGui.QHBoxLayout(qwidget) qwidget.setLayout(qlayout) qscroll = QtGui.QScrollArea(qwidget) qscroll.setGeometry(QtCore.QRect(0, 0, 500, 500)) qscroll.setFrameStyle(QtGui.QFrame.NoFrame) qlayout.addWidget(qscroll) qscrollContents = QtGui.QWidget() qscrollLayout = QtGui.QVBoxLayout(qscrollContents) qscrollLayout.setGeometry(QtCore.QRect(0, 0, 1000, 1000)) qscroll.setWidget(qscrollContents) qscroll.setWidgetResizable(True) for i in xrange(5): qfigWidget = QtGui.QWidget(qscrollContents) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.plot([1,2,3,4]) qscrollLayout.addWidget(qfigWidget) qscrollContents.setLayout(qscrollLayout) qwidget.show() exit(qapp.exec_()) 

Can someone explain why it is not working?

0
source share
1 answer

You create a QWidget for each plot. But you don’t put canvas or toolbar in it through the layout, so they cannot pass size information using QWidget . By default, a QWidget does not have a minimumSize , and the widget / layout inside QScrollArea can make them as small as it wants to fit in the available space (whose size is QScrollArea ).

Adding graphs through the layout helps, but I found that the FigureCanvas widget also does not have a minimum size, so it can contract. For a quick fix, you can set minimumSize . Part of the loop with these fixes should look like this:

 for i in xrange(5): qfigWidget = QtGui.QWidget(qscrollContents) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.plot([1,2,3,4]) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) # prevent the canvas to shrink beyond a point # original size looks like a good minimum size canvas.setMinimumSize(canvas.size()) qscrollLayout.addWidget(qfigWidget) 
+4
source

All Articles