PyQt5 QLabel - Disabling the opacity effect according to the user

PyQt5 QLabel - Disabling the opacity effect according to the user

In PyQt5, to control the opacity of a QLabel, you can use the setWindowOpacity method. However, this method affects the entire window, not just the individual widget. To modify the opacity of just the QLabel, a workaround is to use a QGraphicsOpacityEffect.

Here's how you can apply and control the opacity of a QLabel based on user input, such as using a slider or a button:

import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QSlider, QGraphicsOpacityEffect from PyQt5.QtCore import Qt class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() # Create QLabel self.label = QLabel("This is a QLabel", self) # Create Slider self.slider = QSlider(Qt.Horizontal, self) self.slider.setMinimum(0) self.slider.setMaximum(100) self.slider.setValue(100) # Max opacity self.slider.valueChanged.connect(self.change_opacity) # Layout layout = QVBoxLayout() layout.addWidget(self.label) layout.addWidget(self.slider) self.setLayout(layout) def change_opacity(self, value): # Change the opacity effect of QLabel opacity_effect = QGraphicsOpacityEffect() opacity_effect.setOpacity(value / 100) # Convert to 0-1 range self.label.setGraphicsEffect(opacity_effect) # Create the application object app = QApplication(sys.argv) window = MainWindow() window.show() # Start the main loop sys.exit(app.exec_()) 

In this example:

  • A QLabel and a QSlider are created.
  • The change_opacity method is connected to the valueChanged signal of the slider.
  • Inside change_opacity, a QGraphicsOpacityEffect is created and its opacity is set based on the slider's value.
  • The effect is applied to the QLabel, changing its opacity.

When you run this script, moving the slider will adjust the opacity of the QLabel. The opacity value ranges from 0 (completely transparent) to 1 (completely opaque), and it's controlled by the slider.


More Tags

mysql-error-1052 jql privileges google-cloud-console circular-dependency objective-c menuitem semantic-versioning pod-install upgrade

More Programming Guides

Other Guides

More Programming Examples