想做下面一个效果:想当鼠标移动到按钮上的时候,按钮就变大,图标换个大的,鼠标不在按钮上的时候,按钮就变小,图标也换成小的,感觉比较Cool
实现原理:为每个按钮设置监听属性
void MainHomeForm::init()
{
//为按钮注册事件
ui->SystemSetButton->installEventFilter(this);
ui->ZoneSetButton->installEventFilter(this);
}
//系统监听器监听按钮对象
bool MainHomeForm::eventFilter(QObject *target, QEvent *e)
{
if(target == ui->SystemSetButton)
{
if(e->type() == QEvent::Enter)
{
ui->SystemSetButton->resize(163,91);
QIcon *MouseOnIcon = new QIcon(":/new/prefix1/back/系统设置2.png");
ui->SystemSetButton->setIcon(*MouseOnIcon);
}
else if(e->type() == QEvent::Leave)
{
ui->SystemSetButton->resize(115,60);
QIcon *MouseOffIcon = new QIcon(":/new/prefix1/back/系统设置.png");
ui->SystemSetButton->setIcon(*MouseOffIcon);
}
}
else if(target == ui->ZoneSetButton)
{
if(e->type() == QEvent::Enter)
{
ui->ZoneSetButton->resize(163,91);
QIcon *MouseOnIcon = new QIcon(":/new/prefix1/back/区域控制2.png");
ui->ZoneSetButton->setIcon(*MouseOnIcon);
}
else if(e->type() == QEvent::Leave)
{
ui->ZoneSetButton->resize(115,60);
QIcon *MouseOffIcon = new QIcon(":/new/prefix1/back/区域控制.png");
ui->ZoneSetButton->setIcon(*MouseOffIcon);
}
}
}
搞定,首先绑定按钮的installEventFilter为当前窗体,在窗体的EventFilter事件中,看移到了哪个按钮上面,就可以了。
还有一种就是,当鼠标按下去的时候,移动到按钮上面才会有变化:
//跟踪鼠标移动事件,当鼠标移动到中间的按钮上时,改变图标大小和内容
void MainHomeForm::mouseMoveEvent(QMouseEvent *e)
{
e->accept();
if(enterBtn(e->pos(),ui->SystemSetButton))
{
ui->SystemSetButton->setSizeIncrement(163,91);
QIcon *MouseOnIcon = new QIcon(":/new/prefix1/back/系统设置2.png");
ui->SystemSetButton->setIcon(*MouseOnIcon);
}
}
//自己写的函数,判断鼠标是否在一个按钮区域内
bool MainHomeForm::enterBtn(QPoint pp, QToolButton *btn)
{
int height = btn->height();
int width = btn->width();
QPoint btnMinPos = btn->pos();
QPoint btnMaxPos = btn->pos();
btnMaxPos.setX(btn->pos().x()+width);
btnMaxPos.setY(btn->pos().y()+height);
if(pp.x() >= btnMinPos.x() && pp.y() >= btnMinPos.y()
&& pp.x() <= btnMaxPos.x() && pp.y() <= btnMaxPos.y())
return true;
else
return false;
}