QT按钮鼠标点击触发阴影效果(一)
要求: 给N个不同的按钮,添加鼠标点击后,触发按钮边框加粗、增加阴影效果。
以下方法的缺点:按钮很多就很麻烦,而且点击到别的组件就取消阴影效果了; 下次有空再优化 :)
试了setstylesheet没有阴影效果,也没搜到。
QPushButton:hover,pressed也不太行,checked试了没反应不知道为啥
1、 给N个按钮 安装 事件过滤器 eventFilter
ui->btn1->installEventFilter(this);
8个按钮都添加上
2、 在主窗口 某某某.h 头文件中添加
bool eventFilter(QObject *target, QEvent *e);
3、 在主窗口 某某某.cpp 中添加 事件过滤器代码
先添加#include 阴影效果
不要在函数内定义,就复制到 mainwindow那个大括号之外
最后一句return QMainWindow 某某某 注意不要用错类了。
bool MainWindow::eventFilter(QObject *target, QEvent *e)
{
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);//设置阴影效果
shadow_effect->setOffset(0, 0);
//阴影颜色
shadow_effect->setColor(QColor(135,206,250,222));
//阴影半径
shadow_effect->setBlurRadius(100);
QGraphicsDropShadowEffect *no_shadow_effect = new QGraphicsDropShadowEffect(this);//设置无阴影效果,不知道有没有函数直接disabled,就这样直接设置看不见。。。
no_shadow_effect->setOffset(0, 0);
//阴影颜色
no_shadow_effect->setColor(QColor(255,255,255, 127));
//阴影半径
no_shadow_effect->setBlurRadius(0);
if(target==ui->Btn_1) //
{
if(e->type()==QEvent::MouseButtonPress) //选中按钮1
{
ui->Btn_1->setStyleSheet("background-color:black;border-radius:10px;border:4px solid SkyBlue;");//设置按钮1点击后的样式
ui->Btn_1->setGraphicsEffect(shadow_effect);//设置阴影
ui->Btn_2->setGraphicsEffect(no_shadow_effect);//其他按钮不显示阴影
//N个按钮就重复N次,很麻烦
}
else if (e->type()==QEvent::FocusOut) //未选中按钮1
{
ui->Btn_1->setGraphicsEffect(no_shadow_effect);//设置无阴影效果
ui->Btn_1->setStyleSheet("background-color:black;");//设置回原来的样式
}
}
return QMainWindow::eventFilter(target, e);
}