在动画播放的过程中,要保证对象的存在,即:self.animation创建的对象;
如果使用如下方式,动画将会异常,被释放掉了:
class MyButton(QPushButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._opacity = 0.0
# 1.创建动画
animation = QPropertyAnimation(self, b'opacity')
animation.setDuration(1000)
animation.setStartValue(0.0)
animation.setEndValue(0.9)
animation.setLoopCount(-1)
animation.start()
@pyqtProperty(float)
def opacity(self):
return self._opacity
@opacity.setter
def opacity(self, opacity) -> None:
self._opacity = opacity
t = f'background-color: rgba(0, 0, 0, {opacity})'
self.setStyleSheet(t)
正确的方式如下:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget ,QPushButton
from PyQt5.QtGui import QPixmap, QPainter, QBrush, QPen, QColor
from PyQt5.QtCore import QPropertyAnimation, Qt ,QEasingCurve,QPoint,pyqtProperty
class MyButton(QPushButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._opacity = 0.0
# 1.创建动画
self.animation = QPropertyAnimation(self, b'opacity')
self.animation.setDuration(1000)
self.animation.setStartValue(0.0)
self.animation.setEndValue(0.9)
self.animation.setLoopCount(-1)
self.animation.start()
@pyqtProperty(float)
def opacity(self):
return self._opacity
@opacity.setter
def opacity(self, opacity) -> None:
self._opacity = opacity
t = f'background-color: rgba(0, 0, 0, {opacity})'
self.setStyleSheet(t)
class Window(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('使用插值')
self.resize(500, 500)
self.move(400, 200)
self.setStyleSheet("background-color: red;")
self.btn = MyButton(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())