How to change keyboard's key behavior?
-
Experts,
My question is pretty simple:
I want to press a keyboard's key (on a physical keyboard of-course) and have a custom output.
For example I want to press R on my keyboard and I want to have ® instead.- Is it possible to do such thing generally all over a Qt program?
- If not, is it possible to do it for a widget (something like QLineEdit)?
Thanks in advance
-
@Nouriemm Hi, you can use an event filter for this. Look at this: http://doc.qt.io/qt-5/qobject.html and search for "KeyPressEater". That's an example that's already pretty close to what you want to do. Should be easy to adopt it to your needs.
-
@Wieland
Thanks for the answer.
let us assume that we have done the part of key grabbing like this:bool MainWindow::eventFilter(QObject *target, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_R) { /******what are we suppose to do here ******/ return true; } } return false; }
But, the question is still remained: How to map Qt::Key_R to ® instantly as a general output of the physical keyboard?
-
You can use a sendEvent() simplify. See my sample code: bool MainWindow::eventFilter(QObject *o, QEvent *e) { if (o == ui->lineEdit) { if (e->type() == QEvent::KeyPress) { QKeyEvent *k = static_cast<QKeyEvent*>(e); if (k->key() == Qt::Key_R) { if (k->text().compare("®") != 0) { QKeyEvent ke(k->type(), k->key(), k->modifiers(), QString("®"), k->isAutoRepeat(), k->count()); QApplication::sendEvent(ui->lineEdit, &ke); return true; } } return false; } else { return false; } } else { return MainWindow::eventFilter(o, e); } }
-
Thanks to @Devopia53 and @Wieland the problem has solved.
I have polished the @Devopia53 code to something like this to make it more generic:bool MainWindow::eventFilter(QObject *o, QEvent *e){ if (e->type() == QEvent::KeyPress) { QKeyEvent *k = static_cast<QKeyEvent*>(e); if (k->key() == Qt::Key_R && k->text() != "®") { QKeyEvent ke(k->type(), k->key(), k->modifiers(), QString("®"), k->isAutoRepeat(), k->count()); QApplication::sendEvent(o, &ke); return true; } } return false;
}
Just wondering if my code breaks any rule of programming; Specially by not using
** return MainWindow::eventFilter(o, e);**Cheers
-
@Nouriemm said:
Just wondering if my code breaks any rule of programming; Specially by not using
** return MainWindow::eventFilter(o, e);**When you override event handling, I think calling the parent's method at the end is a good practice, since Qt works on the event and treats special cases (according to the OS for instance) that you may have forgotten.