Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PyQt5 figure canvas doesnt stretch

Problem is my FigureCanvas isnt taking all possible height, it is only reisizing its width. The problem occurs after resizing main window. I would like to let canvas take maximum available height.

This is how it looks now

This is how it looks now

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is minimal reproducible example:

import sys
import os
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtGui import (QPixmap, QPainter, QBrush, QPen, QColor)
from PyQt5.QtCore import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from PyQt5.QtWidgets import *
import matplotlib
from matplotlib import pyplot as plt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Distributions")
        self.setMinimumSize(480, 320)

        # Layout
        mainLayout = QVBoxLayout()
        dirLayout = QHBoxLayout()
        radioLayout = QHBoxLayout()
        canvasLayout = QVBoxLayout()

        # Setting main Widget
        self.mainWidget = QWidget()
        self.setCentralWidget(self.mainWidget)
        self.mainWidget.setLayout(mainLayout)
 

        # Setting canvas to plot
        mainLayout.addLayout(canvasLayout)
        figure = plt.figure()
        canvas = FigureCanvas(figure)

        toolbar = NavigationToolbar(canvas, self)
        canvasLayout.addWidget(toolbar)
        canvasLayout.addWidget(canvas)
        
        plotButton = QPushButton('Plot')
        canvasLayout.addWidget(plotButton, 
        alignment=QtCore.Qt.AlignCenter)
        plotButton.setMaximumSize(QSize(80, 60))
        
app = QApplication(sys.argv)
dialogi = MainWindow()
dialogi.show()
sys.exit(app.exec_())

>Solution :

You have to set the stretch factor when you add the widget to the layout:

canvasLayout.addWidget(canvas, stretch=1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading