Reputation: 1949
My task sounds simple: I want to programmatically press keyboard buttons in Qt/C++. So I want some lines of code that makes the GUI think some keyboard keys was pressed.
I do not want to use windows specific API if possible.
Can this be done? If so how/where should I get started?
Upvotes: 0
Views: 4435
Reputation: 442
The only reliable way to simulate/generate a user key event, is to use the QtTest module.
#include <QtTest>
#define QT_WIDGETS_LIB
#include <qtestkeyboard.h>
...
// For example:
QTest::keyClick(QApplication::focusWidget(), key, Qt::NoModifier);
// or even more low level:
qt_handleKeyEvent(widget->windowHandle(), QEvent::KeyPress, key, Qt::NoModifier);
qt_handleKeyEvent(widget->windowHandle(), QEvent::KeyRelease, key, Qt::NoModifier);
Upvotes: 1
Reputation: 16685
bool MyWidget::event(QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Tab) {
// special tab handling here
return true;
}
} else if (event->type() == MyCustomEventType) {
MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);
// custom event handling here
return true;
}
return QWidget::event(event);
}
This is a simple example from here. The main idea is that you have to send KeyPress event to your window object. Here is another good example.
Upvotes: 0