Search code examples
pythonqt4

Animate using a pixmap or image sequence in Python with QT4


I have a small Python script that makes a transparent window for displaying a graphic on screen and I'd like to animate that graphic, but am entirely unsure how or where to even start. Here's what I do have at least:

import sys
from PyQt4 import QtGui, Qt, QtCore

class Transparent(QtGui.QWidget):

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setAttribute(Qt.Qt.WA_NoSystemBackground)
        self.setAutoFillBackground(True)

        pixmap = QtGui.QPixmap("test1.gif")
                pixmap2 = QtGui.QPixmap("test2.gif")
        width = pixmap.width()
        height = pixmap.height()

        self.setWindowTitle("Status")
            self.resize(width, height)

            self.label = QtGui.QLabel(self)


        def animateEvent():
                    imgnumber = 0
                    try:
                        if imgnumber == 1:
                            self.label.setPixmap(QtGui.QPixmap("test1.gif"))
                            self.setMask(pixmap.mask())
                            imgnumber = 0
                        else:
                            self.label.setPixmap(QtGui.QPixmap("test2.gif"))
                            self.setMask(pixmap2.mask())
                            imgnumber = 1
                    finally:
                        QtCore.QTimer.singleShot(1000, animateEvent)

                animateEvent()


        def paintEvent(self,event):
        self.setAttribute(Qt.Qt.WA_NoSystemBackground)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    x = Transparent()
    x.show()
    app.exec_()

This feels like it has the right ingredients, but the pixmap doesn't update.

I tried QMovie, but then the area of the window that is supposed to be transparent is filled with black instead.


Solution

  • This ended up being a simple correction of an oversight in the end.

    imgnumber needed to be outside of the def as self.imgnumber and needed to be named self.imgnumber each time it was changed.