PDA

View Full Version : keyPressEvent not being called...



bruceariggs
10th October 2011, 17:39
I have a class that doesn't seem to override the keyPressEvent properly, or at least, the function isn't getting called.

It inherits from QDialog



class SelectionDialog : public QDialog


As a public function, it has:



void keyPressEvent( QKeyEvent* event );


Which is defined as:



void SelectionDialog::keyPressEvent( QKeyEvent* event )
{
switch( event->key() )
{
case Qt::Key_Up:
{
upClicked();
break;
}
case Qt::Key_Down:
{
downClicked();
break;
}
default:
{
QDialog::keyPressEvent( event );
break;
}
};
}


In the constructor of my class, I do this



setFocusPolicy( Qt::StrongFocus );
setFocus( Qt::PopupFocusReason );
setEnabled( true );


Yet when this dialog box launches in the program, no amount of key presses gets me into this function.
What am I missing or doing wrong?

wysota
10th October 2011, 20:53
The dialog has to get focus when it is shown and not when it is constructed. Only visible components can have focus.


#include <QtGui>

class Widget : public QWidget {
public:
Widget() : QWidget() { setFocusPolicy(Qt::StrongFocus); }
protected:
void keyPressEvent(QKeyEvent *ke) {
qDebug() << ke->key();
}
};


int main(int argc, char **argv) {
QApplication app(argc, argv);
Widget w;
w.show(); // gets focus automatically since is the only widget shown
return app.exec();
}

bruceariggs
10th October 2011, 21:37
Hey Wysota,

Thanks for the response, but now I have a question about how that can be done.

I display my QDialog by calling exec(), which displays the dialog to the screen, how can I call setFocus() on the Dialog if exec() is what both shows, executes, and closes the window after OK or Cancel is clicked?



SelectionDialog* dialog = new SelectionDialog();

// Too early to set focus?

if( dialog->exec() ) // handles the show and execution
{
// Too late to set focus?
}

wysota
10th October 2011, 21:39
If the dialog doesn't get focus automatically (look out, if there is a default button on the dialog, this button will steal the focus!), you can reimplement showEvent() for the dialog and set focus from within there.