【发布时间】:2023-03-08 03:09:02
【问题描述】:
QPushButton 可以有图标,但我需要为其设置动画图标。这个怎么做?
我创建了从QPushButton 实现的新类,但是如何将图标从QIcon 替换为QMovie?
【问题讨论】:
标签: qt animation icons qt5 qpushbutton
QPushButton 可以有图标,但我需要为其设置动画图标。这个怎么做?
我创建了从QPushButton 实现的新类,但是如何将图标从QIcon 替换为QMovie?
【问题讨论】:
标签: qt animation icons qt5 qpushbutton
由于我今天必须为我的一个项目解决这个问题,我只是想放弃我为未来的人找到的解决方案,因为这个问题有很多观点,我认为该解决方案非常优雅。解决方案已发布here。每次设置pushButton的图标,QMovie的frame都会改变:
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())
【讨论】:
这可以在不继承QPushButton 的情况下通过简单地使用Qt 的信号/槽机制来完成。将QMovie 的frameChanged 信号连接到包含此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 成员时...
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();
【讨论】:
setMovie 切换图标。我认为这会更优雅且与 OOP 一致。