一个简单的qt动画(关键点 animation.setParent(self))

qt动画卡了有段时间,这中间主要要animation.setParent(self)才能正常运行

import sys
from PyQt5.QtCore import Qt, QTimer, QPropertyAnimation, QRect,QEasingCurve
from PyQt5.QtGui import QFont, QPainter
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

class GameWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        self.score = 0
        self.score_label = QLabel(self)
        self.score_label.setFont(QFont('Arial', 20))
        self.score_label.setStyleSheet('color: red')
        self.score_label.move(10, 10)
        self.score_label.setFixedSize(300,100)
        self.update_score()
        
        self.score_effect_label = QLabel(self)
        self.score_effect_label.setFont(QFont('Arial', 30))
        self.score_effect_label.setStyleSheet('color: yellow')
        # self.score_effect_label.setAlignment(Qt.AlignCenter)
        self.score_effect_label.hide()
        self.score_effect_timer = QTimer()
        self.score_effect_timer.timeout.connect(self.hide_score_effect)
        
    def initUI(self):
        self.setGeometry(100, 100, 1300, 1200)
        self.setWindowTitle('Game')
        
    def update_score(self):
        self.score_label.setText(f'Score: {self.score}')
        
    def show_score_effect(self, score_effect):
        self.score_effect_label.setText(score_effect)
        self.score_effect_label.setGeometry(0, self.height() - 100, self.width(), 100)
        self.score_effect_label.show()
        
        animation = QPropertyAnimation(self.score_effect_label, b"geometry")
        animation.setParent(self)
        animation.setDuration(2000)  # 动画持续时间(单位:毫秒)
        animation.setStartValue(QRect(0, self.height() - 100, self.width(), 100))
        animation.setEndValue(QRect(0, self.height() - 500, self.width(), 100))
        animation.setEasingCurve(QEasingCurve.Linear)  # 动画速度曲线
        animation.start()
        
        self.score_effect_timer.start(2000)  # Score effect duration
    def hide_score_effect(self):
        self.score_effect_label.hide()
        self.score_effect_timer.stop()
        
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            self.score += 10
            self.update_score()
            self.show_score_effect('+10')
            
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = GameWindow()
    window.show()
    sys.exit(app.exec_())

你可能感兴趣的:(qt,数据库,开发语言)