This tutorial will focus on how to use PyQt5 to load and display an image in a window. We’ll also cover the necessary steps from setting up the application to dynamically rendering images, ensuring that the process is straightforward and adaptable for various use cases.
Step 1: Install PyQt5
Before we use PyQt5 to display an image , install it by running:
pip install PyQt5
Step 2: Import Required Classes
The specific PyQt5 modules are:
QApplicationto manage the application.QMainWindowto create the main window.QLabelto display the image.QPixmapto handle image loading and rendering.
Step 3: Create the Main Window
We have to define a class to represent the application window. This class will inherit from QMainWindow and include logic to load and display an image.
Step 4: Set Up the Window Layout
In the __init__ method of your window class:
- Setting the title using
setWindowTitle(). - Defining the size and position of the window using
setGeometry().
Step 5: Add a QLabel Widget
We need to create a QLabel to act as a container for the image. Also set its position and dimensions using setGeometry()..
Step 6: Load the Image
Then use QPixmap to load your image file. Most importantly make sure to replace "path_to_your_image.jpg" with the file path of the image you want to display.
Step 7: Display the Image
Then we set the loaded image to the QLabel using the setPixmap() method.
Step 8: Scale the Image (Optional)
If we want the image to adjust to the size of the label, enable the scaling with the setScaledContents(True) method.
Step 9: Launch the Application
Lastly, create a QApplication object to initialize the app . Instantiate the main window class, display the window with show(),, and start the application’s event loop with exec_().
Full Code Example:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt5.QtGui import QPixmap
class ImageDisplayWindow(QMainWindow):
def __init__(self):
super().__init__()
# Set up the window
self.setWindowTitle("Image Viewer")
self.setGeometry(100, 100, 800, 600)
# Add a label to display the image
self.image_label = QLabel(self)
self.image_label.setGeometry(50, 50, 700, 500)
# Load and display the image
image = QPixmap("path_to_your_image.jpg") # Replace with your image path
self.image_label.setPixmap(image)
self.image_label.setScaledContents(True) # Scale image to fit the label
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ImageDisplayWindow()
window.show()
sys.exit(app.exec_())