How to map Qt push button to keyboard key presses.
-
Hi,
I am having a widget with multiple push buttons with characters as name. I want my push button to be active(pressed) when I press a character in keyboard. ie, when I press 'a' in keyboard 'Push_button_A' should get pressed.
Can anyone suggest me a working solution for it.
Thankyou and regards.
-
Hi
Welcome to the forums.Well use a std::map<QString, QPushButton *>
Add all the buttons and its Letter to it.
(you can use FindChildren if you placed them using UI)Set all buttons to Nofocus so they don't eat keys
Override MainWindow KeypressEvent
in keypressEvent function
Look up the button, via the map, and set it to down / or up depending on its stateSomething like that :)
-
Hi and welcome to devnet,
Do you mean that pressing and releasing of the keyboard should be reflected on the button or that the press shall be the same as a mouse button click ?
-
@trojan To catch the key press event subclass QWidget and override https://doc.qt.io/qt-5/qwidget.html#keyPressEvent
In your keyPressEvent you then can then send the click event to the button:QApplication::sendEvent(button, &event);
Or you can simply call the code you're calling when the button is pressed.