⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

[SOLVED] Detect QKeyEvent in every children of a QWidget

  • I'm on a "cash register" app for family business. I have a barcode scanner, touch-screen and a USB numeric keypad.

    In my "cash register" widget, there is few buttons and a QTableView (to show the cart). I need to detect when either "+, -, *, /" keys are pressed, but also any other.

    These 4 keys are "actions" ("plus" will show a list, "minus" will delete the last product, etc...) and any other key (mostly numeric) will show a dialog with a QLineEdit containing any pressed keys until "enter" is pressed (automatically sent by the barcode scanner) to validate a scan or a manual barcode.

    When I've reimplemented MyWidget::keyPressEvent(), it was only detected when the focus was on MyWidget, and the problem is that when you press a button (MyWidget's child) you set the focus on the button, same if you select a line in the QTableView. Is there an efficient way to reimplement keyPressEvent() in the parent widget to listen for all the children's keyPressEvents?

    I tried with QShortcut (as Qt::WindowShortcut) which is fine but I can't detect every other keys. Any idea?

  • Lifetime Qt Champion


    What about an eventFilter that you put on your widgets ?

  • I'll give a try.
    Actually, I thought I would have the same problem with eventFilter (concerning the focus) or maybe you're telling me I will have to install the same eventFilter on every child of my QWidget?

  • Ok... This is strange. The filter successfully detects keyPresses in the widget, no matter which one is focused (between children). But I don't understand why, it only detects modifiers keys :/

    @class CashRegisterEventFilter : public QObject
    bool eventFilter(QObject *obj, QEvent *event)
    if (event->type() == QEvent::KeyPress) {
    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
    qDebug() << "Key pressed:" << (Qt::Key) keyEvent->key();
    return (true);

            return QObject::eventFilter(obj, event);
        CashRegisterEventFilter(QObject *parent) : QObject(parent) {}



    @this->m_eventFilter = new CashRegisterEventFilter(this);

    Debug only shows something when I press "Alt", "Shift", "cmd"... I'm on OS X 10.10.2, any idea?


    Thank you, it's my view's fault. The view already captures the alphanumerical key presses.

    I'm implementing with eventFilter, it seems to be working as expected.

  • Lifetime Qt Champion

    Out of curiosity, are you using several CashRegisterEventFilter ?

Log in to reply