Search code examples
c++qtevent-handlingqkeyevent

can't handle QKeyEvent in Qt C++ when digit and number keys are pressed


I want to do some specific things when user user presses keyboard key .for that I have following code in my program which uses qt and C++ :-

//reimplemented keyPressEvent
// MyWindow inherits from QWidgets 
void MyWindow::keyPressEvent(QKeyEvent *e)
{
        if(e->key()== Qt::Key_3)
        {
              //do something
                QApplication::exit(1);
                std::cout << " presses\n";
        }
}

but this code dose not work.but this code does:-

void MyWindow::keyPressEvent(QKeyEvent *e)
{
        if(e->key()== Qt::Key_Escape)
        {
                QApplication::exit(1);
                std::cout << " presses\n";
        }
 }

Why is this so ?


Solution

  • Add qDebug() << e->key() to the beginning of the method and see exactly what you're getting :). Most likely, the window is not getting the events, but the currently focused widget does.