QT 点击窗口外区域 当前窗口自动关闭

想要通过弹出自定义窗口展示自定义的一些信息,同时也希望像右键菜单一样(点击非菜单区域,菜单自动关闭)的效果,那么你可以按照以下两种方式进行尝试:

设置窗口标识的方式

  • 在构造函数中添加以下代码:
this->setWindowFlags(Qt::Popup);
  • 重写MousePressEvent
void YourDialog::mousePressEvent(QMouseEvent *e)
{
    this->setAttribute(Qt::WA_NoMousReplay);//避免重复触发窗口外的鼠标点击事件(仅关闭窗口)
    QWidget::mousePressEvent(e);
}

关于setAttribute(Qt::WA_NoMousReplay),它会拦截鼠标事件不会传递,专用于弹窗事件

事件过滤的方式

bool YourWidget::event(QEvent * e)
{
	if (QEvent::Show == e->type())
	{
		activateWindow();
	}
	else if (QEvent::WindowDeactivate == e->type())
	{
		this->close();
	}
	return QWidget::event(e);
}

//简版代码
bool ClassName::event(QEvent *event)
{
    if (event->type() == QEvent::ActivationChange)
    {
        if(QApplication::activeWindow() != this)
        {
            this->close();
        }
    }
    return QWidget::event(event);
}

你可能感兴趣的:(Qt,从入门到精通,qt,event,mousePressEvent,WA_NoMousReplay,activeWindow)