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

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

设置窗口标识的方式

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

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

事件过滤的方式

cpp 复制代码
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);
}
相关推荐
龚建波1 天前
《QDebug 2026年6月》
qt
△曉風殘月〆1 天前
如何在Linux中安装Qt开发环境
linux·运维·qt
Quz1 天前
QML 选择控件:Switch、CheckBox 与 RadioButton
qt
熬夜苦读学习1 天前
Qt常用控件
服务器·开发语言·qt
夏玉林的学习之路1 天前
Qt 项目编译错误排查与解决记录
开发语言·qt
Quz2 天前
QML 基础按钮:Button、RoundButton 与 DelayButton
qt
Quz2 天前
QML ToolTip 组件:图标、多行文本与阴影
qt
xcyxiner2 天前
DicomViewer14(读取图像按固定窗宽窗位显示)
qt
马里马里奥-3 天前
从零搭建AI Agent工具链的技术文章大纲
开发语言·qt
Quz3 天前
QML 与 JavaScript 交互方式:内联函数、外部文件、信号槽与工作线程
javascript·qt