python logo

pyqt display image


Python hosting: Host, run, and code Python in the cloud!

In this guide, we will walk you through the steps to load and display images using the Pixmap widget in a PyQT window. Displaying images in PyQt is a common requirement, and the Pixmap widget makes this task straightforward.

PyQt4-loaded-image
Caption: An image displayed within a PyQt4 application.

Recommended course:

Overview

The QPixmap constructor accepts an image path as its parameter. For this to work seamlessly, ensure the image is located in the same directory as your application. Note that the QPixmap widget predominantly supports image formats like PNG and JPEG. Dive into the sample code provided below for a clearer understanding.

How to Display an Image in PyQT Using Pixmap

Begin by setting up a standard QWidget. Following that, incorporate the QPixmap widget, which is responsible for loading the image. This pixmap is then linked to a label, which is subsequently rendered on the screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os
import sys
from PyQt4.QtGui import *

# Set up the main window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Image Display with Pixmap @ pythonspot.com")

# Incorporate the widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())

# Render the window
w.show()
app.exec_()

Want more PyQT code examples?
Download the Comprehensive PyQT Code Collection

Result Image:
pyqt Pixmap Result
Caption: Image shown using the pyqt Pixmap method.

Navigate through our PyQt series:
← Previous | Next →






Leave a Reply:




Jeremy Lee Sat, 23 May 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()

Frank Sat, 23 May 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.