[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?
-
Hi,
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
{
protected:
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); } public: CashRegisterEventFilter(QObject *parent) : QObject(parent) {}
};@
Then:
@this->m_eventFilter = new CashRegisterEventFilter(this);
this->installEventFilter(this->m_eventFilter);@Debug only shows something when I press "Alt", "Shift", "cmd"... I'm on OS X 10.10.2, any idea?
-
NEVERMIND !
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.
-
Out of curiosity, are you using several CashRegisterEventFilter ?