Keyboard letters of a to z are not working in keyPressEvent in Qt

2.8k views Asked by At

I am using KeyPressEvent in my applicatiion. But letters from a to z are not working.

void mywindow::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
        case Qt::Key_Left:
            break;
    }
}

This is working properly

But when I'm using Key_R or Key_L it is not working.

Edit: keyReleaseEvent works with those letters.

2

There are 2 answers

3
Maxim Makhun On

Try this:

void SimpleWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_R)
    {
        // Key R was pressed
    }
}

Or you can simply check key value using QString QKeyEvent::text () const method.

0
epicanriome On

Not sure you still need it, but maybe someone will.

I was in the same situation, when pressing a to z letters none event was sent to my QMainWindow, but ctrl, cmd, alt or esc... was working.

I solved the problem adding this in the constructor.

this->setFocusPolicy ( Qt::StrongFocus );

read setFocusPolicy doc

then

MyQMainWindow::keyPressEvent(:keyPressEvent(QKeyEvent *pevent)
{
    if (pevent->key() == Qt::Key_Control)
        qDebug() << "ctrl pressed";
    if (pevent->key() == Qt::Key_A)
        qDebug() << "a pressed";
}