添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
精明的手套  ·  android int ...·  7 月前    · 
活泼的牛肉面  ·  idea 内置 Node.js idea ...·  1 年前    · 
活泼的手术刀  ·  linux - Python ...·  1 年前    · 
首发于 Qt

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)