如何在Qt5中将动画图标设置为QPushButton?

时间:2013-03-12 23:22:17

标签: qt animation icons qt5 qpushbutton

QPushButton可以有图标,但我需要为其设置动画图标。这该怎么做? 我创建了从QPushButton实施的新课程,但是如何将QIcon中的图标替换为QMovie

2 个答案:

答案 0 :(得分:24)

这可以通过简单地使用Qt的信号/槽机制而无需继承QPushButton来实现。将frameChanged的{​​{1}}信号连接到包含此QMovie的班级中的自定义广告位。此函数将QPushButton的当前帧应用为QMovie的图标。看起来应该是这样的:

QPushButton

分配您的// member function that catches the frameChanged signal of the QMovie void MyWidget::setButtonIcon(int frame) { myPushButton->setIcon(QIcon(myMovie->currentPixmap())); } QMovie成员时......

QPushButton

答案 1 :(得分:0)

由于我今天必须为我的一个项目解决此问题,所以我只想放弃为未来的人找到的解决方案,因为该问题有很多见解,并且我认为该解决方案非常优雅。解决方案已发布here。每次QMovie的框架更改时,都会设置按钮的图标:

auto movie = new QMovie(this);
movie->setFileName(":/sample.gif");
connect(movie, &QMovie::frameChanged, [=]{
  pushButton->setIcon(movie->currentPixmap());
});
movie->start();

这还有一个优点,就是在启动QMovie之前不会显示该图标。这也是我为我的项目派生的python解决方案:

#'hide' the icon on the pushButton
pushButton.setIcon(QIcon())
animated_spinner = QtGui.QMovie(":/icons/images/loader.gif")
animated_spinner.frameChanged.connect(updateSpinnerAniamation)           

def updateSpinnerAniamation(self):
  #'hide' the text of the button
  pushButton.setText("")
  pushButton.setIcon(QtGui.QIcon(animated_spinner.currentPixmap()))

一旦要显示微调器,只需启动QMovie:

animated_spinner.start()

如果微调器应再次消失,则停止动画并再次“隐藏”微调器。动画停止后,frameChanged插槽将不再更新按钮。

animated_spinner.stop()
pushButton.setIcon(QtGui.QIcon())
相关问题