using QKeyEvents (revisited)
Solved
General and Desktop
-
Hi all -
A few months ago, I was experimenting with QKeyEvents, and got a lot of help here. That exercise was ultimately abandoned, but I'd like to revisit it now. So, some of this post may be redundant with my earlier ones.
I'd like to use a keypress/release to show and hide a "secret" button on my main widget. Can I do this without creating a filter? I was thinking of something like this:
void Widget::keyPressEvent(QKeyEvent *event) { int key = event->key(); if (event->type() == QEvent::ShortcutOverride) { if ((key == 'd' || key == 'D')) { ui->pushButtonMcastServer->setVisible(true); } } else if (event->type() == QEvent::KeyRelease) { if ((key == 'd' || key == 'D')) { ui->pushButtonMcastServer->setVisible(false); } } // here I'd like to pass the event to the base class. }
- is this the correct/preferred method of doing this?
- how do I pass the event to the base class?
Thanks...
-
- I would say yes
- As explained in the documentation: calling base class keyPressEvent(), https://doc.qt.io/qt-5/eventsandfilters.html
-
Thanks! For anyone who happens to look this up in the future, the code in my first post contains a few errors. The code posted below is working for me:
void Widget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Alt) { ui->pushButtonMcastServer->setVisible(true); } QWidget::keyPressEvent(event); } void Widget::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Alt) { ui->pushButtonMcastServer->setVisible(false); } QWidget::keyPressEvent(event); }
(Note: I had to switch to a meta-key because the pressing and holding the "D" key caused lots of "D"s to be entered into random editable widgets.)