Question

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...

Was it helpful?

Solution 2

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));
}

OTHER TIPS

[QT_FOLDER]/src/gui/widgets/qpushbutton.cpp : line 459

QPushButton accepts Key_Enter and Key_Return if defaultButton is set to true. I don't know where the space button is changed to something different, but here's my fix:

Create a class MyPushButton and reimplement keyPressEvent. Then just handle Enter and Return with a call to click

It should be very simple.

Edit:

Or if you want fancy, create your own custom events for your device and handle those events in your derived classes exactly as you wish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top