QT 捕獲事件(全局攔截)


QT 捕獲應用鍵盤事件(全局攔截)

主窗口只有一個QTabWidget,
每個tab中嵌入相應的窗口,在使用的過程中,
需要主窗口響應鍵盤事件,而不是tab中的控件響應。
故采取以下方式。

重寫QApplication,使用notify來控制攔截所有事件。


此方法不僅可攔截鍵盤事件,其他事件也可。

 

代碼如下:

 

#include "mainwindow.h"
//#include <QApplication>
#include "application.h"

#include "baselibdefine.h"

int main(int argc, char *argv[])
{
    Application a(argc, argv);

    MainWindow w;
    w.show();
    return a.exec();
}

 

 

#include "application.h"
#include <QDebug>
#include <QTranslator>
#include "baselibdefine.h"

#ifdef Q_QDOC
    Application::Application(int &argc, char **argv)
        :QApplication(argc, argv)
    {

    }
#else
    Application::Application(int &argc, char **argv, int flag)
    :QApplication(argc, argv, flag)
    {
        connect(this, &Application::signal_keyPress, &w, &MainWindow::slot_keyPressed);
    }
#endif

Application::~Application()
{

}

bool Application::notify(QObject *obj, QEvent * event)
{
    if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (!keyNumberPress(keyEvent))
        {
            emit signal_keyPress(keyEvent);
            return true;
        }
    }
    else if (event->type() == QEvent::KeyRelease)
    {
        return true;
    }

    return QApplication::notify(obj, event);
}


bool Application::keyNumberPress(QKeyEvent * keyEvent)
{
    if (keyEvent->key() == Qt::Key_0
            || keyEvent->key() == Qt::Key_1
            || keyEvent->key() == Qt::Key_2
            || keyEvent->key() == Qt::Key_3
            || keyEvent->key() == Qt::Key_4
            || keyEvent->key() == Qt::Key_5
            || keyEvent->key() == Qt::Key_6
            || keyEvent->key() == Qt::Key_7
            || keyEvent->key() == Qt::Key_8
            || keyEvent->key() == Qt::Key_9
            || keyEvent->key() == Qt::Key_Backspace
            || keyEvent->key() == Qt::Key_Delete)
    {
        return true;
    }

    return false;
}

 

#ifndef APPLICATION_H
#define APPLICATION_H

#include <QApplication>
#include "mainwindow.h"

class Application : public QApplication
{
    Q_OBJECT
public:
#ifdef Q_QDOC
    Application(int &argc, char **argv);
#else
    Application(int &argc, char **argv, int flag = ApplicationFlags);
#endif

    virtual ~Application();

private:
    bool keyNumberPress(QKeyEvent *);

protected:
    bool notify(QObject *obj, QEvent *event) Q_DECL_OVERRIDE;

public:
    MainWindow w;

signals:
    void signal_keyPress(QKeyEvent *keyEvent);
};

#endif // APPLICATION_H

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM