Label,PushButton,ToolButton 实现动态图片按钮,Label显示gif动画
.h文件
public:
explicit event(QWidget *parent = 0);
~event();
QImage image;
QLabel *label;
QLabel *label2;
QPixmap p2;
QPalette pl;
QIcon icon;
QToolButton *btn;
QPushButton *pb;
public slots:
bool eventFilter(QObject*,QEvent*);
.cpp文件
image.load(":/images/x.png");
p2.load(":/images/xx.png");
label = new QLabel(this);
label->setPixmap(QPixmap::fromImage(image));
pb = new QPushButton(this);
pb->setFlat(true);//去边框
icon.addPixmap(p2);
pb->setIcon(icon);//设置背景
pb->setIconSize(p2.size());
/* *********另一种设置背景******
pb->setObjectName("pb");//使以下的作用域只作用于pb
pb->setStyleSheet("QPushButton#pb{border-image:url(:/images/1.png)}QPushButton::pressed#pb{border-image:url(:/images/100.png)}");
*/
btn = new QToolButton (this);
btn->setText("test");
btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);//文字与图片下方显示
btn->setIcon(p2);
btn->setAutoRaise(true);//去边框
btn->setIconSize(p2.size());
QGridLayout *lay = new QGridLayout(this);
lay->addWidget(label,0,0);
lay->addWidget(btn,1,1);
lay->addWidget(pb,2,2);
lay->setMargin(10);
/*************控件安装过滤器***********/
label->installEventFilter(this);
pb->installEventFilter(this);
btn->installEventFilter(this);
/*************显示GIF动画****************/
label2= new QLabel(this);
label2->setGeometry(350,50,150,213);
QMovie *movie = new QMovie(":/images/32.gif");
label2->setMovie(movie);
movie->start();
}
bool event::eventFilter(QObject*w,QEvent*e)
{
if(w == label)
{
if(e->type() == QEvent::MouseButtonPress)
{
QMatrix ma;
ma.scale(0.5,0.5);
QImage im = image.transformed(ma);
label->setPixmap(QPixmap::fromImage(im));
}
if(e->type() == QEvent::MouseButtonRelease)
{
label->setPixmap(QPixmap::fromImage(image));
}
}
if(w == btn)
{
if(e->type() == QEvent::MouseButtonPress)
{
QMatrix ma;
ma.scale(0.8,0.8);
QPixmap px = p2.transformed(ma);
icon.addPixmap(px);
btn->setIcon(px);
}
if(e->type() == QEvent::MouseButtonRelease)
{
btn->setIcon(p2);
}
}
if(w ==pb)
{
if(e->type() == QEvent::MouseButtonPress)
{
QMatrix ma;
ma.scale(0.8,0.8);
QPixmap px = p2.transformed(ma);
icon.addPixmap(px);
pb->setIcon(px);
}
if(e->type() == QEvent::MouseButtonRelease)
{
pb->setIcon(p2);
}
}
return QDialog::eventFilter(w,e);
}