方式一:也是最简单有效的方法是设置窗口标志位。 setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); Qt::Popup表明此窗口为最上层模态窗口,点击子窗口之外的位置都会自动隐 藏,类似于菜单的效果。需要注意的是,使用move(point)函数来移动子窗口时,需要用全局坐标,虽然它的父对象没有变,但是坐标变成了全局坐标,需使用move(mapToGlobal(point))。 方式二:重写窗口[virtual] bool QObject::event(QEvent *e) 该方式很简单,但是有一个弊病,需要为每个要实现该功能的窗口都重写该函数。 bool Form::event(QEvent *event) { if (event->type() == QEvent::ActivationChange) { if(QApplication::activeWindow() != this) { this->close(); } } return QWidget::event(event); } 方式三:重写[virtual] bool QObject::eventFilter(QObject *watched, QEvent *event) 步骤一:为每个要实现该功能的窗口安装事件过滤void QObject::installEventFilter(QObject *filterObj),一般在构造函数里安装; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //f和f1都是窗口类实例 f=new Form; f1=new Form1; f->installEventFilter(this); f1->installEventFilter(this); } 步骤二:重写事件过滤函数 bool MainWindow::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::ActivationChange) { if(watched == f || watched == f1)//需要实现该功能的控件 { if(QApplication::activeWindow() != watched) { QWidget *w=static_cast<QWidget *>(watched); w->close(); } } } return QMainWindow::eventFilter(watched, event); } 这样就在父窗口里实现了每个子窗口的点击窗口外关闭该窗口的功能,这样的实现还有一个缺陷,注册了事件过滤的窗口类只能有一个窗口可以显示,在打开其他窗口的同时会自动关闭现有激活的子窗口。 重构: 重构原则 重构原则二 如何重构(一) 设计原则: 设计模式之七大设计原则 创建型设计模式: 设计模式之单例模式 设计模式之工厂模式 设计模式之原型模式 设计模式之建造者模式 结构型设计模式: 设计模式之桥接模式 设计模式之适配器模式 设计模式之外观模式 设计模式之组合模式 设计模式之代理模式 设计模式之享元模式 行为型设计模式: 设计模式之观察者模式 设计模式之策略模式 设计模式之模板模式 ---------------------------------------------------------------------------------------------------------------------- 我们尊重原创,也注重分享,文章来源于微信公众号:跟田老师学C++,建议关注公众号查看原文。如若侵权请联系qter@qter.org。 ---------------------------------------------------------------------------------------------------------------------- |