[Python] Change background of QTextEdit with a duration [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    General overview


    I try to make a read only QTextEdit change his background color with a keybinding event. The goal is to make A make the background progressively goes from blue to white.

    The problem


    So, it works with the following MWE, but the animation didn’t respect the duration. It’s instantaneous.

    Minimal working example


    import sys
    from PyQt6.QtWidgets import QApplication, QLabel, QTextEdit
    from PyQt6.QtCore import QPropertyAnimation, Qt
    from PyQt6.QtGui import QPalette, QColor

    class AnimatedLabel(QTextEdit):
    def __init__(self, text):
    super().__init__(text)
    self.setReadOnly(True) # Readonly to catch the keystroke

    self.setStyleSheet("background: blue; background-color 3s;") # Color of the bigining

    #\
    self.anim = QPropertyAnimation(self, b"styleSheet") #| This
    self.anim.setDuration(9000000) #| is the
    self.anim.setStartValue("background: blue; background-color 3s;") #| relevant
    self.anim.setEndValue("background: white; background-color 3s;") #| part
    #/

    def keyPressEvent(self, event):
    # Keystroke detection for « A »
    if event.key() == Qt.Key.Key_A:
    print("Pressed")
    self.anim.start()

    app = QApplication(sys.argv)
    label = AnimatedLabel("Foo bar")
    label.show()
    sys.exit(app.exec())


    The question


    How to make the background change progressive? I search to make a fading effect.

    Edit


    Also if I use palette deffenition method like in the following code, the transition take effect but didn’t respect the duration:

    palette = QPalette()

    palette.setColor(QPalette.ColorRole.Base, QColor(Qt.GlobalColor.red)) # Couleur de fond du QTextEdit
    palette.setColor(QPalette.ColorRole.Text, QColor(Qt.GlobalColor.black))
    self.setPalette(palette)

    self.anim = QPropertyAnimation(self, b"palette") #| This
    self.anim.setStartValue(QColor(Qt.GlobalColor.black)) #| relevant
    self.anim.setEndValue(QColor(Qt.GlobalColor.white)) #| part
    self.anim.setDuration(9000000) #| is the

    Continue reading...

Compartilhe esta Página