C++ (Qt)void QObject::childEvent ( QChildEvent * event )
void QObject::childEvent ( QChildEvent * event )
void QObject::installEventFilter ( QObject * filterObj )
C++ (Qt) class MainWindow : public QMainWindow { public: MainWindow(); protected: bool eventFilter(QObject *obj, QEvent *ev); private: QTextEdit *textEdit; }; MainWindow::MainWindow() { textEdit = new QTextEdit; setCentralWidget(textEdit); textEdit->installEventFilter(this); } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == textEdit) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); qDebug() << "Ate key press" << keyEvent->key(); return true; } else { return false; } } else { // pass the event on to the parent class return QMainWindow::eventFilter(obj, event); } }
C++ (Qt)bool MainWindow::eventFilter(QObject *obj, QEvent *ev){ qDebug("%s, %d",qPrintable(obj->objectName()),ev->type()); return QMainWindow::eventFilter(obj,ev);} void MainWindow::childEvent( QChildEvent* e){ switch (e->type()) { case QEvent::ChildAdded: e->child()->installEventFilter(this); break; case QEvent::ChildRemoved: e->child()->removeEventFilter(this); break; default: break; } QMainWindow::childEvent(e);}
Window::Window(){ QCoreApplication::instance()->installEventFilter( this );}void Window::keyPressEvent( QKeyEvent * e ){ qDebug() << "key event:" << e->key();}bool Window::eventFilter( QObject * o, QEvent * e ){ if ( o->isWidgetType() && (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) ) { QKeyEvent * ke = static_cast<QKeyEvent*>( e ); QWidget * w = static_cast<QWidget*>( o ); if ( w != this && isAncestorOf( w ) ) { if ( ke->key() == Qt::Key_C || ke->key() == Qt::Key_Left || ke->key() == Qt::Key_Right ) { QCoreApplication::instance()->sendEvent( this, ke ); return true; } } } return false;}