How to set animated icon to QPushButton in Qt5?

Robotex picture Robotex · Mar 13, 2013 · Viewed 10.7k times · Source

QPushButton can have icon, but I need to set animated icon to it. How to do this? I created new class implemented from QPushButton but how to replace icon from QIcon to QMovie?

Answer

Sir Digby Chicken Caesar picture Sir Digby Chicken Caesar · Mar 13, 2013

This can be accomplished without subclassing QPushButton by simply using the signal / slot mechanism of Qt. Connect the frameChanged signal of QMovie to a custom slot in the class that contains this QPushButton. This function will apply the current frame of the QMovie as the icon of the QPushButton. It should look something like this:

// member function that catches the frameChanged signal of the QMovie
void MyWidget::setButtonIcon(int frame)
{
    myPushButton->setIcon(QIcon(myMovie->currentPixmap()));
}

And when allocating your QMovie and QPushButton members ...

myPushButton = new QPushButton();
myMovie = new QMovie("someAnimation.gif");

connect(myMovie,SIGNAL(frameChanged(int)),this,SLOT(setButtonIcon(int)));

// if movie doesn't loop forever, force it to.
if (myMovie->loopCount() != -1)
    connect(myMovie,SIGNAL(finished()),myMovie,SLOT(start()));

myMovie->start();