PyQt - QGraphicsColorize Effect



The color effect is commonly used in GUI to distinguish the specific element and enhance overall user experience.

In PyQt, QGraphicsColorize class is used to apply a colorize effect to graphics items in a QGraphicScene. This class is used to alter the color items and inherited from the class QGraphicsEffect.

Let's dive into detail theory of QGraphicsColorize Effect −

A colorized effect renders the source with a shade of its color. We can modify the color using the method setColor(). This function accepts the method QColor as a parameter to set the color to graphical item such as text, rectangle, line, etc.

By default, the color is light blue i.e. RGB(0, 0, 192).

Advantages of using QGraphicsColorize Effect in PyQt

  • We can dynamically change the item color during runtime.
  • Using QColorizeEffect provides visual feedback to users. For example- indicating a valid input.
  • The shadow appearance of widgets looks interactive.
  • Consistency of style on a custom widgets can be beneficial for the software development process.

Example

In this example, we will provide a code snippet for changing the color of the text when a button is clicked.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, 
QPushButton, QVBoxLayout, QGraphicsColorizeEffect
from PyQt6.QtGui import QColor
class color_effect(QWidget):
   def __init__(self):
      super().__init__()

      # Initialize the UI
      self.initUI()
   def initUI(self):
      # Set window properties
      self.setWindowTitle('PyQt')
      self.setGeometry(150, 150, 450, 250)

      # Create a label
      self.label = QLabel('Welcome to Tutorialspoint', self)

      # Create a button
      self.colorize_button = QPushButton('Click Here', self)
      self.colorize_button.clicked.connect(self.applyColorizeEffect)

      # Set up the layout
      layout = QVBoxLayout()
      layout.addWidget(self.label)
      layout.addWidget(self.colorize_button)
      layout.addStretch()
      self.setLayout(layout)
   def applyColorizeEffect(self):
      # Create a colorize effect
      colorize_effect = QGraphicsColorizeEffect()
      # Set the darkgreen color
      colorize_effect.setColor(QColor(0, 100, 0))
      # Apply the effect to the label
      self.label.setGraphicsEffect(colorize_effect)

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

Output

The above code produces the following output −

colorize effect
Advertisements