How to set animated icon to QPushButton in Qt5?

2020-05-20 09:57发布

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?

1条回答
Melony?
2楼-- · 2020-05-20 10:43

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();
查看更多
登录 后发表回答