Keyboard hooks / event filters on Qt


A special keyboard is used to navigate through a Qt program. The keyboard has only arrows and Enter key.
The program has several buttons (with only one it could be set as prefered and thus Enter would work)
he mouse can not be used and

At first glance the function “void keyPressEvent( QKeyEvent *k );” seems better at first glance but in practice it doesn’t allow asking for the object generating the event and the keys do different things depending on where they are pressed.

In the .h file:

	    bool eventFilter(QObject *object, QEvent *event);

In the cpp file:

ui->password->installEventFilter(this); // I also want to move to the next input box with the down arrow key.

ui->validate->installEventFilter(this); // The buttons are activated with Space key instead of Enter key

bool userpass::eventFilter(QObject *object, QEvent *event){

    QKeyEvent *k = static_cast(event);

    if (event->type() == QEvent::KeyPress)

	 if (object == ui->password ) {
            if(k->key() == Qt::Key_Down || k->key() == Qt::Key_Enter || k->key() == Qt::Key_Return ){
                //  qDebug("Going down");

	  if (object == ui->validate ) {         
           if (k->key() == Qt::Key_Enter || k->key() == Qt::Key_Return ){
                qDebug("Trying to log in");
                // validate is a button and the buttons are activated with Spacebar instead of Enter key.
                // So I create an artificial key event and I send it to the object who received enter.
                QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Space, Qt::NoModifier);
                QCoreApplication::postEvent (object, event);
    } // end of keypress events.

    return 0;
	/* How to get the native keycode on Linux and XWindow:
	   On XWindow for keys without a Qt name, use the command "showkey" and do +8 to it.
	   Then use nativeScanCode. (native for Xwindow that is. For the kernel is nativeScanCode-8)
	   example: if(k->nativeScanCode()==36 || k->nativeScanCode()==114 ){ ...


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s