Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always have focus policy on hidden widget? (Qt C++)

Tags:

c++

qt

qkeyevent

I am learning to process keypress and keyrelease events in Qt (C++). I have a class Keyboard with which I want to process all of these events. It inherits QObject. It doesn't need to process any mouse events. I am trying to figure out how I can direct all of the keyboard input when my application is open to that class.

I've tried adding it as a widget in a layout of my MainWindow class and hiding it (the widget, not the layout). Currently, that is not responding.

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's not working either. In my Keyboard::Keyboard() constructor, I have:

this->setFocusPolicy(Qt::StrongFocus);

I'm not sure if there's anything else I need to do to make sure the keyboard input gets there.

If someone knows a way to send all keyboard events to this class for my Qt application, it would be very helpful!

Thanks,

John

like image 281
John Avatar asked Aug 23 '14 23:08

John


1 Answers

For anyone who wants to know, I found the answer to my question.

In the constructor for the class that is handling my keyboard events, I added this line:

QWidget::grabKeyboard();

and now all the keyboard input when that application is active goes straight to that widget. You can check the reference for more information: QWidget::grabKeyboard.

Note: nothing else (i.e., no other widgets) will get keyboard input until you call QWidget::releaseKeyboard().

like image 146
John Avatar answered Sep 27 '22 15:09

John