How to Show Images in PyQt

Posted by

Displaying Images in PyQt

Displaying Images in PyQt

PyQt is a set of Python bindings for the Qt application framework and runs on all platforms supported by Qt including Windows, OS X, Linux, iOS, and Android. It’s a great tool for creating desktop applications with a graphical user interface.

One common task in PyQt is displaying images in your application. Fortunately, PyQt makes this task quite simple. You can easily display images using the QLabel widget, which is a widget for displaying text or an image.

Example:

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

class ImageDisplay(QMainWindow):
    def __init__(self):
        super().__init__()

        # Create a QLabel widget
        label = QLabel(self)

        # Load an image using QPixmap
        pixmap = QPixmap('image.jpg')

        # Set the image to the label
        label.setPixmap(pixmap)
        label.setScaledContents(True)

        # Create a layout and add the label to it
        layout = QVBoxLayout()
        layout.addWidget(label)

        # Set the layout for the main window
        main_widget = QWidget()
        main_widget.setLayout(layout)
        self.setCentralWidget(main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ImageDisplay()
    window.show()
    sys.exit(app.exec_())
    
  

In this example, we create a QMainWindow and add a QLabel widget to it. We then load an image using QPixmap, set the image to the label, and add the label to the layout. Finally, we set the layout for the main window and display the window.

With just a few lines of code, we are able to display an image in our PyQt application. This makes PyQt a powerful tool for creating desktop applications with image display capabilities.

Overall, displaying images in PyQt is a simple and straightforward process. By using the QLabel widget and QPixmap, you can easily incorporate images into your PyQt applications, making them more visually appealing and user-friendly.