I have a custom input device on and embedded system, and have to translate the input to proper events in Qt. In my current view I have a QListView and some QPushButtons. I use the following code in my widget.
QKeyEvent * e = NULL;
if (cmd.up.value)
e = new QKeyEvent(QEvent::KeyPress, Qt::Key_Up, 0, 0);
else if (cmd.down.value)
e = new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, 0, 0);
else if (cmd.left.value)
e = new QKeyEvent(QEvent::KeyPress, Qt::Key_Left, 0, 0);
else if (cmd.right.value)
e = new QKeyEvent(QEvent::KeyPress, Qt::Key_Right, 0, 0);
else if (cmd.ok.value)
e = new QKeyEvent(QEvent::KeyPress, Qt::Key_Space, 0, 0);
if (e)
QApplication::postEvent(this->focusWidget(), e);
I can move up/down/right/left between list and buttons, but I can't click the buttons. I've tried using Qt::Key_Enter and Qt::Key_Return as well, but neither works.
If run the application on my pc, hitting space or the left mouse button on my keyboard gives a button click. That indicates that somewhere, the event is changed to something the pushbutton likes better than getting a Qt::Key_Space directly, right?
Anyone got an idea for how I can solve this nicely? I can check which (if any) button has focus and click it manually, but that is not very elegant coding...
The solution to this was actually quite simple. A QPushButton isn't clicked on KeyPress, but on KeyRelease. New code below.
if (cmd.up.value)
{
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyPress, Qt::Key_Up, 0, 0));
}
else if (cmd.down.value)
{
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, 0, 0));
}
else if (cmd.left.value)
{
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyPress, Qt::Key_Left, 0, 0));
}
else if (cmd.right.value)
{
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyPress, Qt::Key_Right, 0, 0));
}
else if (cmd.ok.value)
{
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyPress, Qt::Key_Space, 0, 0));
QApplication::postEvent(this->focusWidget,
new QKeyEvent(QEvent::KeyRelease, Qt::Key_Space, 0, 0));
}