PyQt - Opacity Effect



Opacity defines the level of transparency of any particular element. You may have heard of this property in web technology i.e. CSS which uses the property of opacity with its value.

In PyQt, we can implement a GUI technique that correlates the property of transparency. The effect of opacity in GUI is established through the class QGraphicsOpacityEffect which can be used to set the transparency level.

Here, we have two functions to explore the opacity effect in PyQt −

  • setOpacity(opacity) − This function sets the opacity effect.
  • setOpacityMask(mask) − This function hold the opacity mask of the effect. Using opacity mask allows users to apply opacity on selective element.

Benefits of using QGraphicsOpacityEffect

Following are some key benefit of using QGraphicsOpacityEffect −

  • Subtle Animations − We can create smooth animation for UI element(fade-in and face-out) that enhance the user experience.
  • Depth and Layer − Adjusting of opacity can be achieved through layering effects. For instance, we can overlap text on an image with reduced opacity to create depth.
  • Highlighting − The effect of opacity reduce to highlight specific element like tooltip and pop-ups.
  • Visual Effect − The visual effect intracts the desktop application. This appeal the effects like glass panel, frosted glass, and transulent overlays.

Now, we can create a simple PyQt program to demonstrate the setOpacity() function.

Example 1

In this example, we illustrate the opacity effect on text using PyQt.

import sys
from PyQt6.QtWidgets import QApplication, QLabel, 
QGraphicsOpacityEffect, QVBoxLayout, QWidget

app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()

label = QLabel("Welcome to Tutorialspoint")
opacity_effect = QGraphicsOpacityEffect()
# set the opacity
opacity_effect.setOpacity(0.7) 
label.setGraphicsEffect(opacity_effect)

layout.addWidget(label)
window.setLayout(layout)
window.show()

sys.exit(app.exec())

Output

The above code produces the following output −

opacity effect example one

Example 2

In this example, we illustrate the opacity effect on images in PyQt.

import sys
from PyQt6.QtWidgets import QApplication, QLabel, 
QGraphicsOpacityEffect, QVBoxLayout, QWidget
from PyQt6.QtGui import QPixmap

app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()

# Set the path
image_path = 'C:/Users/Lenovo/Downloads/tutorialspoint.png'
image_label = QLabel()
image_pixmap = QPixmap(image_path)
image_label.setPixmap(image_pixmap)

# Create a QGraphicsOpacityEffect
opacity_effect = QGraphicsOpacityEffect()
# Setting Opacity
opacity_effect.setOpacity(0.5)  
image_label.setGraphicsEffect(opacity_effect)

layout.addWidget(image_label)
window.setLayout(layout)
window.show()

sys.exit(app.exec())

Output

The above code produces the following output −

opacity effect example one
Advertisements