有些时候我们希望通过鼠标点击窗口外部来关闭当前窗口,这里主要用到两种方法;
- [virtual] bool QObject::event(QEvent *e);
- [virtual] bool QObject::eventFilter(QObject *watched, QEvent *event);
方式一:重写窗口[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);
}
这样就在父窗口里实现了每个子窗口的点击窗口外关闭该窗口的功能,这样的实现还有一个缺陷,注册了事件过滤的窗口类只能有一个窗口可以显示,在打开其他窗口的同时会自动关闭现有激活的子窗口