Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Toggling QPixmap image



  • Hi,

    I need to display a "flashing" QPixmap.
    I currently have a static pixmap that gets displayed like so: self.Lab1Icon.setPixmap(self.red) and I want it to toggle between two different pixmaps (let's say self.red & self.clr). How do I best go about this? Should I use the QTimer class' interval feature and update a global to toggle between two states?


  • Lifetime Qt Champion

    Hi,

    No, globales are not needed. Just have a list containing your various pixmap, a counter and in the slot you connect to your QTimer, increment the counter and set the new current image on your label. All of them shall be class members.



  • I came up with something like the below, and while it does work functionally, it still makes use of a global to keep the state of the list between two function calls:

    import sys
    from PyQt4.QtGui import *
    from PyQt4.QtCore import QTimer
    
    # Create an PyQT4 application object.
    a = QApplication(sys.argv)
    
    # The QWidget widget is the base class of all user interface objects in PyQt4.
    w = QWidget()
    
    # Set window size.
    w.resize(320, 240)
    
    # Set window title
    w.setWindowTitle("Hello World!")
    
    redPM = QPixmap('red.gif')
    clrPM = QPixmap('clr.gif')
    listPM = [ redPM, clrPM ]
    lbl = QLabel('Hello World!', w)
    lbl.move(100, 80)
    lbl.setPixmap(redPM)
    lbl.resize(lbl.sizeHint())
    i = 0
    
    def toggle():
        global i
        if i == 1:
            lbl.setPixmap(listPM[0])
            i=0
        else:
            lbl.setPixmap(listPM[1])
            i=1
    
    tmr = QTimer()
    tmr.timeout.connect(toggle)
    tmr.setInterval(500)
    tmr.start()
    
    
    
    
    # Show window
    w.show()
    
    sys.exit(a.exec_())
    

    Mh now thinking about it, would it be more ressource efficient to display an animated gif as QMovie instead?


  • Lifetime Qt Champion

    That depends on how many of these you are going to have and their size.



  • @SGaist I'm going to have only one for the time being. The size is 118x118.but I'm actually going to leave it as I have it above as it offers easy flexibility to adjust the frequency as required. As always, Thanks for your help!


  • Lifetime Qt Champion

    You're welcome !

    Since you have it working the way you want it, please mark the thread as solved using the "Topic Tool" button or the three doted menu beside the answer you deem correct so other forum users may know a solution has been found.


Log in to reply