TestMenu派生自QMenu,popUp显示出来后,期望点击程序其它位置时,主动关闭该界面。通过事件过滤器,可以很方便的实现。
具体代码如下:
bool EventFilter::eventFilter(QObject *watched, QEvent *event) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
QPoint globalPos = mouseEvent->globalPos();
QPoint localPos = menu->mapFromGlobal(globalPos);
if (menu && menu->isVisible()) {
if(!menu->rect().contains(localPos))
menu->close();
}
}
return QObject::eventFilter(watched, event);
}
TestMenu::TestMenu(QWidget *parent):QMenu(parent){
setAttribute(Qt::WA_TranslucentBackground);
setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
this->setStyleSheet(menuBgQSS);
filter = new EventFilter(this);
qApp->installEventFilter(filter);
}
TestMenu::~TestMenu(){
qApp->removeEventFilter(filter);
}