Qt开发中,有些组件的事件往往没有,比如QMenu并没有click事件,那么我们便可以通过事件过滤,来给QMenu处理click事件,包括QLabel,QLineEdit等等,下面摘取Qt帮助文档里的一段代码,仅供参考:
bool QObject::eventFilter ( QObject * watched, QEvent * event ) [virtual]
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); } }
文章的脚注信息由WordPress的wp-posturl插件自动生成