Python – How to load and show a rescaled image with pyqt4

pyqt4pythonqt4

A similar question was asked here, but without description how to rescale the image. I only found the C++ specs for QPixmap so far, and a reference guide for pyQT4. But the latter does not seem to have any reference to QPixmap.

Question: Does anyone know how to show a rescaled version of the full image based on the code in the first link, and/or where I can find the pyQt4 specs?

Best Answer

You could use the QPixmap.scaledToHeight or QPixmap.scaledToWidth method:

import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setGeometry(0, 0, 400, 200)
pic = QtGui.QLabel(window)
pic.setGeometry(10, 10, 400, 200)
pixmap = QtGui.QPixmap(FILENAME)
pixmap = pixmap.scaledToHeight(200)
pic.setPixmap(pixmap)

window.show()
sys.exit(app.exec_())    

You can find documentation on PyQT classes (including QPixmap) here.

Sometimes when I am lazy and do not want to read documentation, I use this:

def describe(obj):
    for key in dir(obj):
        try:
            val = getattr(obj, key)
        except AttributeError:
            continue
        if callable(val):
            help(val)
        else:
            print('{k} => {v}'.format(k = key, v = val))
        print('-'*80)

pixmap = QtGui.QPixmap(FILENAME)
describe(pixmap)

which prints lots of output about all the attributes of the object passed to describe. In this case, you can find relevant methods by searching for the string -> QPixmap since these are the methods that return a new QPixmap. That's how I found scaledToHeight and scaledToWidth.