Always have a focus policy on a hidden widget? (Qt C ++)
I am learning to handle keypress and keyrelease events in Qt (C ++). I have a Keyboard class that I want to handle all these events with. It inherits QObject. It doesn't need to handle mouse events. I am trying to figure out how I can route all keyboard input when my application is open to this class.
I tried to add it as a widget to the layout of my MainWindow class and hide it (widget, not layout). This is currently unresponsive.
I've also tried this in my MainWindow class:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
keys->keyPressEvent(event);
//Keys is a Keyboard object with this public method:
//void keyPressEvent(QKeyEvent *event);
}
But that doesn't work either. In my Keyboard :: Keyboard () constructor, I have:
this->setFocusPolicy(Qt::StrongFocus);
I'm not sure if there is something else I need to do to make sure the input on the keyboard gets there.
If anyone knows a way to send all keyboard events to this class for my Qt application, that would be very helpful!
Thank,
John
source to share
For those who want to know, I found the answer to my own question.
In the constructor of the class that handles my keyboard events, I added this line:
QWidget::grabKeyboard();
and now all keyboard input when this app is active goes straight to this widget. You can check the link for more information: QWidget :: grabKeyboard .
Note: nothing else (i.e. other widgets) will enter the keyboard until you name it QWidget::releaseKeyboard()
.
source to share