Qt 工程中处理Alt+F4键,关闭当前顶层界面的问题

可以单独写一个事件过滤类,然后需要屏蔽Alt+F4键的界面,添加事件过滤到这个类上。

class Handler : public QObject
{
    Q_OBJECT
public:
    explicit Handler(QObject *parent = 0);
    static Handler* GetInstance();
protected:
    bool eventFilter(QObject *watched, QEvent *event) override;
private:
    bool flag;
};
Handler* Handler::GetInstance()
{
    static Handler handler;
    return &handler;
}
Handler::Handler(QObject *parent) : QObject(parent)
{
    this->installEventFilter(this);
}

bool Handler::eventFilter(QObject *watched, QEvent *event)
{
    auto type = event->type();
    switch (type) {
    case QEvent::KeyPress:
        key_type = static_cast<QKeyEvent*>(event)->key();
        if(key_type == Qt::Key_Alt )
            flag = true;
        break;
    case QEvent::KeyRelease:
        key_type = static_cast<QKeyEvent*>(event)->key();
        if(key_type == Qt::Key_Alt)
          flag = false;
        break;
    case QEvent::Close:
        if(flag)
        {
            event->ignore();
        }
        break;
    default:
        break;
    }
    return true;
}
使用方式
 Widget w;
 w.installEventFilter(Handler::GetInstance());
这样就可以屏蔽w界面的Alt+F4,消息,其他消息也可以通过这个消息处理类来完成

猜你喜欢

转载自blog.csdn.net/jiaojinlin/article/details/83374965