Qt eventFilter无法过滤mouse事件

最近做了个测试发现Qt 的eventFilter无法过滤mouse事件,如mouseMove, mousePress, mouseRelease等,
原来是installEventFilter(QObject *)安装不对。看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);
     }
 }
这里eventFilter接受的是QEvent::KeyPress事件,打印event->type发现始终获得不到mouse事件,
原来因为QTextEdit是由QAbstractScollArea派生的,对于QAbstractScollArea,其过滤器要安装在viewport上,
因此上面程序变换如下即可过滤mouse event:

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);
     textEdit->viewPort->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 if (obj == textEdit->viewPort())
     {
          // To do.....
         if (event->type() == QEvent::mouseMove) 
         {
              return true;
         }
     } 
    else 
    {
        // pass the event on to the parent class
        return QMainWindow::eventFilter(obj, event);
    }
 }


发布了29 篇原创文章 · 获赞 20 · 访问量 34万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览