analitics

Pages

Sunday, May 11, 2025

Python Qt6 : simple animation with sprites.

Today I created with addon for Blender 3D and result is an image with sprites ...
I used that image with sprites and PyQt6 to animate my desktop screen, see the result:
This is the source code I used:
import sys
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QMenu

# diff PyQt6 versus old PyQt
from PyQt6.QtGui import QAction

from PyQt6.QtGui import QPixmap, QIcon
from PyQt6.QtCore import QTimer, Qt

class AnimatedWindow(QWidget):
    def __init__(self):
        super().__init__()

        # set window
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        # build layout 
        layout = QVBoxLayout()
        self.label = QLabel(self)
        layout.addWidget(self.label)
        self.setLayout(layout)

        # load sprite sheet from Camera_256px.png file name
        sprite_sheet = QPixmap("Camera_256px.png")  
        self.frame_width = sprite_sheet.width() // 11  # because I have 11 sprite on image
        self.sprites = [sprite_sheet.copy(i * self.frame_width, 0, self.frame_width, sprite_sheet.height()) for i in range(11)]
        self.current_frame = 0

        # 
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_animation)
        self.timer.start(150)  # Schimbă frame-ul la fiecare 150 ms

        # 
        self.resize(self.frame_width, sprite_sheet.height())

        # left down on screen 
        screen = QApplication.primaryScreen().geometry()
        self.move(10, screen.height() - self.height() - 10)

    def update_animation(self):
        """Actualizează sprite-ul în QLabel"""
        self.label.setPixmap(self.sprites[self.current_frame])
        self.current_frame = (self.current_frame + 1) % len(self.sprites)

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