1 - About the QPixmap PyQt5 class

A QPixmap is one of the widgets used to manage and manipulate images. It is optimized to display images on the screen. In our sample code, we'll use the QPixmap to display an image on the window. A QPixmap object can also be loaded into another widget, typically a label or button. The Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulation. Pixmap, on the other hand, is optimized to display image on the screen.

2 - Insert an Image with the QPixmap PyQt5 class

To insert an image on a PyQt5 window you must: 

  1. import the QPixmap class from PyQt5.QtGui 
  2. create an instance object of the QPixmap class 
  3. associate the QPixmap instance object with a QLabel via the setPixmap() method:

Example

Now let's create a folder named 'images/' and put inside an image 'laptop.png' and then create a python file to visualize the image: show-image.py

from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
import sys

app = QApplication(sys.argv)
root = QWidget()
root.setGeometry(100 , 100 , 500 , 300)

# create a QPixmap object
qpixmap = QPixmap("./images/laptop.png")
# creat a QLabel for image
lbl_img = QLabel(root)
lbl_img.setGeometry(50 , 20 , 300 , 300)
lbl_img.setPixmap(qpixmap)

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

3 - Resizing image

You can also resize the image via the resize method applied to the QLabel containing the image:

Example

# resizing the image
lbl_img.setScaledContents(True)
lbl_img.resize(75 , 75)

4 - QPixmap according to the object approach

Based on the syntax for creating and inserting an image via the QPixmap class, we can completely recode it in a single Python class:

from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
import sys

class MyWindow(QWidget):
def __init__(self, win):
super().__init__()
self.win = win

def build(self):
self.win.setWindowTitle("Example of QPixmap")
self.win.setGeometry(100 , 100 , 500 , 300)

# create a QPixmap object
self.img = QPixmap("./images/laptop.png")

# create a QLabel for image
self.lbl_img = QLabel(self.win)
self.lbl_img.setScaledContents(True)

# set the QPximap object to the label image
self.lbl_img.setPixmap(self.img)
self.lbl_img.resize(75 , 75)

if __name__ == '__main__':
app = QApplication(sys.argv)
root = QWidget()
mywin = MyWindow(root)
mywin.build()
root.show()
sys.exit(app.exec_())
Younes Derfoufi
my-courses.net

Leave a Reply