Search code examples
user-interfaceqtqt4

Qt4: QTableView mouse button events not caught


I have a QTableView in which I am displaying a custom model. I would like to catch right mouse clicks so that I can open a contextual drop down menu on the underlying table data:

MainWindow::MainWindow()
{
  QTableView * itsView = new QTableView;
  itsView->installEventFilter(this);
  ... //Add other widgets and display them all
}

bool MainWindow::eventFilter(QObject * watched, QEvent * event)
{
  if(event->type() == QEvent::MouseButtonPress)
    printf("MouseButtonPress event!\n");
  else if(event->type() == QEvent::KeyPress)
    printf("KeyPress event!\n");
}

Strangely, I get all of the KeyPress events properly: when I have a cell highlighted and press a key, I get the "KeyPress event!" message. However, I only get the "MouseButtonPress event!" message when I'm clicking on the very thin border surrounding the entire table.


Solution

  • It's because the Tableview is this thin border... If you want to access the widget's content, you should instead install your eventFilter on the Tableview's viewport !

    I therefore propose :

    QTableView * itsView = new QTableView;
    itsView->viewport()->installEventFilter(this);
    

    Try this, it should fix your problem !

    Hope it helps !