需求:QTtoolButton 鼠标移到按钮上时,弹窗菜单,并且点击菜单或者其他地方,菜单关闭后,按钮的hover状态需要恢复原状。
1. 创建按钮和菜单,并安装事件过滤器
m_Menu = new QMenu(); m_Menu->addAction(ui->action22); m_Menu->installEventFilter(this); m_ToolButton =new QToolButton(this); m_ToolButton->setPopupMode(QToolButton::InstantPopup); m_ToolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); m_ToolButton->setDefaultAction(ui->action1); m_ToolButton->setMenu(m_Menu); m_ToolButton->installEventFilter(this); //安装事件过滤器
2.在事件过滤器中,处理消息,关键点是设置WA_UnderMouse为false。
bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == m_ToolButton) { //如果鼠标进入,弹出菜单 if (event->type() == QEvent::HoverEnter) { m_ToolButton->showMenu(); //弹出菜单 } } else if(obj == m_Menu) { //菜单隐藏后 if (event->type() == QEvent::Hide) { //关键点,需要设置WA_UnderMouse为false,让按钮认为不在鼠标下,然后再发送QEvent::HoverLeave消息,才会起到恢复hover状态的作用。 m_ToolButton->setAttribute(Qt::WA_UnderMouse, false); QHoverEvent hoverEvent(QEvent::HoverLeave, QPoint(10, 10), QPoint(0, 0)); QCoreApplication::sendEvent(m_ToolButton, &hoverEvent); } } return QWidget::eventFilter(obj, event); }
标签:QTtoolButton,菜单,Qt,Menu,按钮,ToolButton,QEvent,鼠标 From: https://www.cnblogs.com/SamFang/p/18337056