Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synthesize key press events?

I am able to get key value's from HAL through a call back function in Qt. Created event for that key by

QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, 
                                  inputKey.keyValue, 
                                  Qt::NoModifier);

Note: inputKey.keyValue Key value received from HAL Layer.

Now I need to Register This key event in Qt, So that if any key press happened in IR Remote then in respective form, keyPressEvent(e) or event(e) will get invoke. and based on the key press, specific action will get execute.

Note: More than one form is there, where key press event will trigger And more than one keys are there "Page_Up, Page_Down, Ok Key etc....."

tried to invoke Postevent() and connect(.......) but nothing helped me. KeyPressEvent() is not getting executed.

like image 854
Lalatendu Avatar asked Sep 04 '25 17:09

Lalatendu


1 Answers

E.g. like this:

// receiver is a pointer to QObject
QCoreApplication::postEvent (receiver, event);

You can find more info here.

You can reimplement QObject::event() or QWidget::keyPressEvent in your widget to receive key events. Visit this link or link for more information. See the example code below which consists of two buttons and a label. Clicking pushButton sends 'enter pressed' and pushButton_2 sends 'letter A pressed'. Key events are received in the event() function and label is updated accordingly.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(sendKeyEvent()));
    connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(sendKeyEvent()));
}

void MainWindow::sendKeyEvent()
{
    QObject* button = QObject::sender();
    if (button == ui->pushButton)
    {
        QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
        QCoreApplication::postEvent (this, event);
    }
    else if (button == ui->pushButton_2)
    {
        QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, Qt::Key_A, Qt::NoModifier);
        QCoreApplication::postEvent (this, event);
    }
}

bool MainWindow::event(QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Enter) {
            ui->label->setText("Enter received");
            return true;
        }
        else if (keyEvent->key() == Qt::Key_A)
        {
            ui->label->setText("A received");
            return true;
        }
    }

    return QWidget::event(event);
}
like image 119
talamaki Avatar answered Sep 07 '25 11:09

talamaki