Qt 鼠标在窗口外区域点击时关闭窗口
鼠标在窗口外区域点击时,关闭该窗口。想要实现这样的功能,大致有以下几种思路:
- 重写鼠标点击事件 (mousePressEvent()),若鼠标位置不在该窗口区域内,关闭窗口
- 重写焦点失去事件 (focusOutEvent()),若窗口失去焦点,关闭窗口
- 设置窗口属性为 Qt::Popup,可自动实现窗口外点击关闭窗口
this->setWindowFlags(Qt::Popup);
Qt::Popup
Indicates that the widget is a pop-up top-level window, i.e. that it is modal, but has a window system frame appropriate for pop-up menus.
Qt::Popup 表示该 widget 是弹出式顶级窗口,即它是模态的,但具有适合弹出菜单的窗口系统框架。
- 重写事件函数 (event() ),收到窗口停用事件 (QEvent::WindowDeactivate) 时,关闭窗口
bool MyWidget::event(QEvent * eve)
if (QEvent::WindowDeactivate == eve->type())
this->close();
return QWidget::event(eve);
这个思路还有另外一种写法:收到窗口状态改变事件时,判断该窗口是否为活动窗口 (active window)。
bool MyWidget::event(QEvent * eve)
if (QEvent::ActivationChange == eve->type())
if(QApplication::activeWindow() != this)