QT开发中文网

c++ qt 当点击窗口外的地方时 关闭窗口 用eventfilter

可以使用QEventFilter来实现在点击窗口外的地方时关闭窗口。

首先,在窗口类的构造函数中,添加以下代码:

this->installEventFilter(this);

这将会使当前窗口对象成为事件过滤器。

接下来,重写事件过滤器方法:

bool MyWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if (!this->geometry().contains(mouseEvent->globalPos())) {
            this->close();
            return true;
        }
    }
    return false;
}

在这个方法中,我们判断鼠标按下事件是否发生在当前窗口内。如果不是,则关闭当前窗口并返回true,表示该事件已经被处理了。如果是,则返回false,表示该事件需要进一步处理。

最后,在窗口类的析构函数中,移除事件过滤器:

this->removeEventFilter(this);

完整示例代码如下:

#include <QtWidgets>

class MyWindow : public QMainWindow
{
public:
    MyWindow(QWidget *parent = nullptr) : QMainWindow(parent)
    {
        this->installEventFilter(this);
    }

    ~MyWindow()
    {
        this->removeEventFilter(this);
    }

protected:
    bool eventFilter(QObject *obj, QEvent *event) override
    {
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (!this->geometry().contains(mouseEvent->globalPos())) {
                this->close();
                return true;
            }
        }
        return false;
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyWindow window;
    window.setGeometry(100, 100, 300, 200);
    window.show();

    return app.exec();
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=2805

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?