keyPressEvent() isn't being called
-
In my
main.cpp
I declare aMainWindow
object, and show it:MainWindow mainWindow; mainWindow.showWindow();
This object is a screen with 4 buttons (say screen 1). I connected the buttons with the Enter key so once clicked they open a new screen (2):
connect(buttons[0], SIGNAL (released()), this, SLOT (openExample()));
In that new screen I can either press ESC and return to the previous screen (which works by using
installEventFilter()
and implementingeventFilter()
), or press ENT and go to the next new screen (3).That last thing is not working for me (pressing ENT in screen 2 to go to screen 3).
This is what I've done:
Screen 3:
ExampleSettings::ExampleSettings(QWidget *parent) : Settings(parent) { QVBoxLayout* exampleSettingsLayout = new QVBoxLayout(&widget); for(int i=0; i<BUTTONS_NUMBER; i++) { buttons[i] = new QLabel(); } buttons[0]->setText(tr("SETTING 1")); buttons[1]->setText(tr("SETTING 2")); for(int i=0; i<BUTTONS_NUMBER; i++) { exampleSettingsLayout->addWidget(buttons[i]); } exampleSettingsLayout->installEventFilter(this); }
and declared
keyPressEvent()
:public: void keyPressEvent(QKeyEvent *event);
and defined it:
void ExampleSettings::keyPressEvent(QKeyEvent *event) { cout << "got event!" << endl; }
but it's not being called.
I think the problem is in installing the event filter. Maybe because
exampleSettingsLayout
is dead after the constructor finishes? but I also tried to make it a member variable of the class, and it didn't work (keyPressEvent()
still not called).edit:
I also triedeventFilter()
instead ofkeyPressEvent()
, but also this one isn't invoked. -
Hi,
It's uncommon to install an event filter on a layout. It's the widgets that usually get keyboard focus thus the key related events.
-
I see.
Indeedwidget.installEventFilter(this);
worked, but witheventFilter()
and notkeyPressEvent()
.
I don't understand howeventFilter()
is activated and the conditionif (event->type() == QEvent::KeyPress)
is met, but on the other handkeyPressEvent()
isn't invoked.
The disadvantage witheventFilter()
is that it's always triggered. Can anything be done to trigger onlykeyPressEvent()
? -
Well, that's the use of eventFilter. In your reimplementation, you check only for what you are interested in and when it's not just call the base class implementation.