PDA

View Full Version : Detect Arrow Keys



Ebonair
9th November 2009, 05:42
Hello, I am porting some Qt software from Linux to Windows. It went smoothly, except for two problems:

1) I had to comment out this line of code, that made my QGraphicsView render with OpenGL:

gui.graphicsView->setViewport(new QGLWidget);

If it was enabled, at runtime I would get warning: ASSERT: "dst.depth() == 32" in file qgl.cpp, line 1688

2) My program no longer detects arrow keystrokes. I can see they're being consumed by the QGraphicsView, because they wrongly cause the user to scroll through the graphics view. In Linux, the problem was solved by adding
gui.graphicsView->setFocusPolicy(Qt::NoFocus); In Windows, it doesn't help. Could it be because I am no longer using OpenGL? All other keystrokes are still detected normally, like so:
void MainWindow::keyPressEvent(QKeyEvent *keyEvent){...}

What should I do?

squidge
9th November 2009, 08:16
Have you tried installing an event filter?

Ebonair
9th November 2009, 20:09
I have now, with great success. ;) Thank you very much.

I've seen a few other people have posted about this problem, so here is the solution I used:



gui.graphicsView->installEventFilter(this);

void MainWindow::keyReleaseEvent(QKeyEvent *keyEvent)
{
...
}//keyReleaseEvent

void MainWindow::keyPressEvent(QKeyEvent *keyEvent)
{
...
}//keyPressEvent

bool MainWindow::eventFilter(QObject *obj,
QEvent *event)
{
QKeyEvent *keyEvent = NULL;//event data, if this is a keystroke event
bool result = false;//return true to consume the keystroke

if (event->type() == QEvent::KeyPress)
{
keyEvent = dynamic_cast<QKeyEvent*>(event);
this->keyPressEvent(keyEvent);
result = true;
}//if type()

else if (event->type() == QEvent::KeyRelease)
{
keyEvent = dynamic_cast<QKeyEvent*>(event);
this->keyReleaseEvent(keyEvent);
result = true;
}//else if type()

//### Standard event processing ###
else
result = QObject::eventFilter(obj, event);

return result;
}//eventFilter

Now arrow keystrokes that were being eaten by the QGraphicsView are being passed to my event handlers, as they should be. If you are having problems detecting arrow keys, they are probably being eaten by another widget, and this solution should work.

mhoover
1st October 2010, 02:40
I tried the eventFilter solution above, when a QComboBox gets focus it never forwards it to the event handler.

mhoover
1st October 2010, 03:55
Ah ... the problem was I tried to install the eventFilter on a widget with a bunch of children who didn't get the installation.

I brute forced it:


for ( int i = 0; i < sub_control->sub_sub_control.children().size(); i++ ) {
sub_control->sub_sub_control.children()[ i ]->installEventFilter( this );
}