QWidget how to receive keyPressEvent inside child widgets

gmuhammad picture gmuhammad · Oct 14, 2014 · Viewed 16.8k times · Source

I have one main Widget and inside this main widget I have QListWidget and two buttons. I have override the keyPressEvent inside the main widget (inherited from QWidget). I can receive the keyPress events when focus is not on QListWidget, but when focus is inside the QListWidget I am unable to receive these keyPress events. Below is the code I have used to achieve this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setFocusPolicy(Qt::StrongFocus);

    ui->listWidget->addItem(new QListWidgetItem("Item1"));
    ui->listWidget->addItem(new QListWidgetItem("Item2"));
    ui->listWidget->addItem(new QListWidgetItem("Item3"));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "event->key(): " << event->key();

    QWidget::keyPressEvent(event);
}

Answer

Kosovan picture Kosovan · Oct 14, 2014

In header:

protected:

     bool eventFilter(QObject *obj, QEvent *event);

In constructor:

qApp->installEventFilter(this);

Filter:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{   
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
           qDebug() << "key " << keyEvent->key() << "from" << obj; 
    }
    return QObject::eventFilter(obj, event);
}

With this event filter you can catch all key press events and check who is emit event (obj)

For example:

if ( obj == ui->listWidget )
//event from QListWidget

Accordingly to your comment:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{ 
    if (event->type() == QEvent::KeyPress)
    {
        if(obj == ui->listWidget)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if(keyEvent->key() == Qt::Key_Up)
                qDebug() << "Up";
            if(keyEvent->key() == Qt::Key_Down)
                qDebug() << "Down";
        }
    }
    return QObject::eventFilter(obj, event);
}