PyQt QPixmap

QPixmap is a widget used to handle images. The file formats supported are as follows: Some image formats can only be 'read'.

Supported formats are bitmap (bmp), gif, jpg, jpeg, png, pbm, pgm, ppm, xbm and xpm. Using QPixmap, we're able to display a single image in a window.

Related course: Create Desktop Apps with Python PyQt5

QPixmap

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

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        pixmap = QPixmap('computer.jpg')

        lbl_img = QLabel()
        lbl_img.setPixmap(pixmap)
        lbl_size = QLabel('Width: '+str(pixmap.width())+', Height: '+str(pixmap.height()))
        lbl_size.setAlignment(Qt.AlignCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(lbl_img)
        vbox.addWidget(lbl_size)
        self.setLayout(vbox)

        self.setWindowTitle('QPixmap')
        self.move(300, 300)
        self.show()

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

One image appears in the widget window.

load image in python pyqt window qpixmap

Related course: Create Desktop Apps with Python PyQt5

Description

pixmap = QPixmap('computer.jpg')

Enter a file name and create a QPixmap object (pixmap).

lbl_img = QLabel()
lbl_img.setPixmap(pixmap)

Create one label and use setPixmap to set the pixmap as the image that will appear on the label.

lbl_size = QLabel('Width: '+str(pixmap.width())+', Height: '+str(pixmap.height()))
lbl_size.setAlignment(Qt.AlignCenter)

width() and height() return the width and height of the image.

Create a label (1) that displays lbl_size height, and set it to center alignment using the setAlignment method.

vbox = QVBoxLayout()
vbox.addWidget(lbl)
self.setLayout(vbox)

Create one horizontal box layout and place labels.

Use setLayout() to specify the horizontal box (hbox) as the layout of the window.