How to emit signal when detecting TAB key press?
-
Hello all,
I am creating an interface which controlled only by keyboard. I have edit the tab order properly so far and focusing widget is changing when pressing tab key. My problem is I could not use the "Enter" key on focus widget. I thought if I will be able to emit signal when the tab key press, than I can detect the which widget has focused and emitting the different signals based on the focused widget.
Up to now, I tried the "focusInEvent", "focusOutEvent" and "keyPressEvent" but unfortunately I couldn't make it work. If you suggest the different method, I would like to hear it. Any help or idea would be appreciated. -
@hix_boz @Christian-Ehrlicher is correct, that event hast to be overwritten in the object that has the focus.
alternatively, you could use the code as a general eventFilter, installed on your QApplication
https://doc.qt.io/qt-5/qobject.html#installEventFilter
or on your tabed widgets -
You can override QWidget::keyPressEvent() and emit a signal there.
-
hi @hix_boz and welcome
@hix_boz said in How to emit signal when detecting TAB key press?:
"focusInEvent", "focusOutEvent" and "keyPressEvent"
how did you do that? can you share some code and explain more what did not work as expected, because at the very least overriding KeyPressEvent should have worked!
-
Hello @J-Hilk,
I used "keyPressEvent" like this and I did not get any reply.
void MainWindow::keyPressEvent(QKeyEvent *event){ qDebug() << "Key Pressed" << event->key(); QKeyEvent* key = static_cast<QKeyEvent*>(event); if(key->key() == Qt::Key_Tab){ qDebug() << "Tab is pressed"; } }
-
You have to catch the keyPressEvent() on the widgets where you want to catch the Tab-Key and not on the MainWindow which contains those widgets.
-
@hix_boz @Christian-Ehrlicher is correct, that event hast to be overwritten in the object that has the focus.
alternatively, you could use the code as a general eventFilter, installed on your QApplication
https://doc.qt.io/qt-5/qobject.html#installEventFilter
or on your tabed widgets -
Thanks for the reply. How do I do what you suggest? I got buttons on centralwidget in mainwindow. I want to know just which button focused. Could you explain that simple code snippet?
-
@hix_boz said in How to emit signal when detecting TAB key press?:
How do I do what you suggest?
In the same way you did for MainWindow.
If yaou need this for QPushButton, then subclass QPushButton, override keyPressEvent there and use that custom button instead of QPushButton.