A lot of widgets seems to have default behavior for the space bar key press event. How can I override this without subclassing every widget?

Shaheer Khan Source

I have a very specific piece of code that needs to be executed instantly, no matter what else is going on in the gui, when the space bar is pressed. I have the following snippet of code in each of my keypress event filters:

    else if(keyPressed == Qt::Key_Space){
    emit sigHalted();
}

This works fine, unless certain widgets have focus. The ones causing me issues are: QTableWidget QPushButton

If I'm editing an in a QTableWidget, and I hit space bar, then it adds a space bar to the item in the QTableWidget instead of executing the code above. If I click a button with the mouse, and then hit space bar, it acts as if I clicked that same button again instead of executing the code above.

I know I can fix this behavior by subclassing the widgets and overriding their event filters, but I would prefer to avoid this, because I have a lot of buttons and tables and I would have to go through and replace all of them with the new, subclassed versions. Is there a way I can catch the space bar keypress event before it goes to the widget's default behavior?

c++qt

Answers

answered 2 years ago eyllanesc #1

You must use eventFilter.

  • Enable the event:

code:

#include <QApplication>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qApp->installEventFilter(this);
}
  • Declare the function:

code:

bool eventFilter(QObject *watched, QEvent *event);
  • Override the function:

code:

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{

    if (event->type() == QEvent::KeyPress){
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Escape){
            //your code here
            emit sigHalted();
            return true;
        }
        else{
            return false;
        }
    }
    else
        return QMainWindow::eventFilter(watched,event);
}

comments powered by Disqus