pyqt5 动画学习(二) 改变控件颜色

上一篇我们通过  self.anim = QPropertyAnimation(self.label, b"geometry")创建了一个动画,改变了空间的大小,这次我们来改变控件的颜色

但是label是没有color这个动画属性的,即设置  self.anim = QPropertyAnimation(self.label, b"color")是无效的

为此,我们要重写label类,赋予一个color属性,例如:

class MyLabel(QLabel):
    def __init__(self, text, para):
        super().__init__(text, para)

    def _set_color(self, col):
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), col)
        self.setPalette(palette)

    color = pyqtProperty(QColor, fset=_set_color)

还是通过调色板来改变label的颜色, 然后我们自定义一个名为"color"的属性

color = pyqtProperty(QColor, fset=_set_color)

定义以后我们就可以正常使用这个属性了,例如

self.anim = QPropertyAnimation(self.label, b"color")

下面是程式完整代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 Animation tutorial

This program animates the color of a
widget with QPropertyAnimation.

Author: Seshigure 401219180@qq.com
Last edited: 2018.03.02
"""

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyLabel(QLabel):
    def __init__(self, text, para):
        super().__init__(text, para)

    def _set_color(self, col):
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), col)
        self.setPalette(palette)

    color = pyqtProperty(QColor, fset=_set_color)


class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.button = QPushButton("Start", self)
        self.button.clicked.connect(self.doAnim)
        self.button.move(30, 30)

        self.label = MyLabel("changeColor", self)
        self.label._set_color(QColor(255, 50, 50, 50))
        self.label.setGeometry(150, 30, 100, 100)

        self.setGeometry(300, 300, 380, 300)
        self.setWindowTitle('Animation')
        self.show()

    def doAnim(self):
        self.anim = QPropertyAnimation(self.label, b"color")
        self.anim.setDuration(3000)
        self.anim.setStartValue(QColor(255, 50, 50, 50))  # 粉色 
        self.anim.setKeyValueAt(0.5, QColor(255, 0, 0, 250))  # 红色
        self.anim.setEndValue(QColor(255, 250, 50, 50))  # 米黄
        self.anim.start()


if __name__ == "__main__":
    app = QApplication([])
    ex = Example()
    ex.show()
    app.exec_()

界面预览图如下:

备注:

1、label没有color动画属性,所以我们得重写label

2、self.anim.setKeyValueAt(0.5, QColor(255, 0, 0, 250))这里使用了一个关键帧,让动画完成 粉色>红色>米黄的颜色转换

 
原文地址:https://www.cnblogs.com/semishigure/p/8491966.html