Search code examples
pythonqtpyqtpysidepixmap

How to set maximum widths and heights for pixmaps?


I have a window displaying an image, like this:

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        pixmap = QtGui.QPixmap("image.jpg")

        pixmapShow = QtGui.QLabel(self)
        pixmapShow.setPixmap(pixmap)

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(pixmapShow, 0, 1)

        self.setGeometry(400, 400, 400, 400)
        self.setWindowTitle('Review')    
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())

How can I set a maximum width and a maximum height allowed for displaying the pixmaps?

  • If the image is wider than 350 pixels or taller than 200 pixels, the image should be scaled down until one dimension is equal than 350 pixels, with the aspect ratio maintained.
  • If the image is smaller than 350x200, then no scaling occurs.

Solution

  • You could define your own Pixmap container class which automatically scales the pixmap, based on the resize event.

    class PixmapContainer(QtGui.QLabel):
        def __init__(self, pixmap, parent=None):
            super(PixmapContainer, self).__init__(parent)
            self._pixmap = QtGui.QPixmap(pixmap)
            self.setMinimumSize(1, 1)  # needed to be able to scale down the image
    
        def resizeEvent(self, event):
            w = min(self.width(), self._pixmap.width())
            h = min(self.height(), self._pixmap.height())
            self.setPixmap(self._pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio))
    

    Then in your code, it's pretty straigthforward:

    def initUI(self):
    
        pixmapShow = PixmapContainer("image.jpg")
        pixmapShow.setMaximumSize(350, 200)
    
        grid = QtGui.QGridLayout(self)
        grid.setSpacing(10)
        grid.addWidget(pixmapShow, 0, 1)
    
        self.setGeometry(400, 400, 400, 400)
        self.setWindowTitle('Review')    
        self.show()