QT4 Pixmaps (Images)


In this article we will demonstrate how to load and display images in an PyQT window. We can display images in a PyQT window using the Pixmap widget.

PyQt4-load-image
An image loaded in a PyQt4 window.

Download PyQT Code (Bulk Collection)

Introduction

The constructor of Pixmap takes the image path as parameter:

pixmap = QPixmap(os.getcwd() + '/logo.png')

This image needs to be in the same directory as your program. The QPixmap widget supports png and jpeg.  Example code below.

PyQT load image in Pixmap

We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.

import os
import sys
from PyQt4.QtGui import *
 
# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ") 
 
# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())
 
# Draw window
w.show()
app.exec_()

Result:

pyqt Pixmap
pyqt Pixmap


2 thoughts on “QT4 Pixmaps (Images)

  1. Jeremy Lee - May 23, 2015

    At least on Windows – this hangs without response to ^C if logo does not exist.
    Added simple error check

    import os
    import sys
    from PyQt4.QtGui import *
     
    # Create window
    app = QApplication(sys.argv)
    w = QWidget()
    w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ") 
     
    # Create widget
    label = QLabel(w)
    picfile='logo.png'
    logo = os.getcwd() + '\\' + picfile
    print logo
    if os.path.isfile(logo):
    	pixmap = QPixmap(logo)
    	label.setPixmap(pixmap)
    	w.resize(pixmap.width(),pixmap.height())
     
    	# Draw window
    	w.show()
    	app.exec_()
    else:
    	print "I expected to find a png picture called logo.png in "+ os.getcwd()
    1. Frank - May 23, 2015

      Hi Jeremy, after changing to the correct quotes and changing the \\ to /, this program works fine under Linux.
      Did you try with other image formats such as JPG or GIF? Make sure the quotes are correct.