PyQt5 - How to add image in window?

PyQt5 - How to add image in window?

To add an image to a window using PyQt5, you'll typically use the QLabel widget in combination with QPixmap. Here's a step-by-step guide to demonstrate this:

  1. Install PyQt5: If you haven't already installed PyQt5, you can do so using pip:

    pip install pyqt5 
  2. Sample Code to Add an Image:

    import sys from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget from PyQt5.QtGui import QPixmap from PyQt5.QtCore import Qt class ImageWindow(QMainWindow): def __init__(self): super().__init__() # Load the image into a QPixmap pixmap = QPixmap('path_to_image.jpg') # Replace with your image path # Create a QLabel widget to display the image image_label = QLabel(self) image_label.setPixmap(pixmap) image_label.setAlignment(Qt.AlignCenter) # Set the main layout layout = QVBoxLayout() layout.addWidget(image_label) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) # Set window properties self.setWindowTitle("PyQt5 Image Display") self.setGeometry(100, 100, 800, 600) app = QApplication(sys.argv) window = ImageWindow() window.show() sys.exit(app.exec_()) 

    Replace 'path_to_image.jpg' with the path to your image file.

  3. Run the Code: Execute the Python script. A window will appear displaying the image.

Here's a breakdown of the code:

  • We subclass QMainWindow to create a custom main window.
  • Within our custom window's constructor (__init__ method):
    • A QPixmap object is created to load the image.
    • A QLabel widget is then used to display this QPixmap.
    • We set the QLabel containing the image as the central widget of the main window.
    • We also set some properties for the main window, such as the title and initial size.

By running the script, a PyQt5 window will pop up displaying the image you specified. Adjust the window size, image path, and other properties as needed.


More Tags

ecmascript-harmony days grepl self-signed hbm2ddl numeric-input dropzone.js powerquery numerical-integration bitmapimage

More Programming Guides

Other Guides

More Programming Examples