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
时间: 2024-10-10 20:58:41