Qt编程获取鼠标移动事件

想做下面一个效果:想当鼠标移动到按钮上的时候,按钮就变大,图标换个大的,鼠标不在按钮上的时候,按钮就变小,图标也换成小的,感觉比较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;
}


  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值