Important: Please read the Qt Code of Conduct -

QKeyPress - Simulating key press

  • Re: [SOLVED] QKeyPress - Simulating key press

    I tried the same approach, but not able to get written on the lineEdit widget

        QKeyEvent *key_press = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_X, Qt::NoModifier);
    QApplication::sendEvent(ui->lineEdit, key_press);


    QApplication::postEvent(ui->lineEdit, key_press);

    also didn't succeed.

    I tried the below also and didn't get any result.

    QKeyEvent key(QEvent::KeyPress, Qt::Key_X, Qt::NoModifier);
    QApplication::sendEvent(ui->lineEdit, &key);
    if (key.isAccepted()) {
          qDebug()<<"everything is ok";
    } else {
          qDebug()<<"something wrong";

    Please suggest what am I missing.


  • Lifetime Qt Champion

    For my keyboard i do like this

    auto FOCUSOBJ = QGuiApplication::focusObject();
    QString keyStr(QKeySequence(key).toString()); // key is int with keycode
    QKeyEvent pressEvent = QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, keyStr);
    QKeyEvent releaseEvent = QKeyEvent(QEvent::KeyRelease, key, Qt::NoModifier);
    QCoreApplication::sendEvent(FOCUSOBJ, &pressEvent);
    QCoreApplication::sendEvent(FOCUSOBJ, &releaseEvent);

    which makes keyboard type into editlines etc.

  • Hi,
    got it done.

    QKeyEvent *key_press = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_X, Qt::NoModifier, "x");

    the last parameter "x"

  • @sayan275 Dear Sayan I think you may know the answer to my problem. I'm struggling to send a self-defined event from main.cpp to the ui->boardView in mainwindow.cpp, as the ui->boardView is only defined in mainwindow.cpp. Yet the eventfilter can only be installed on the ui->boardView. It seems you've done similar sth similar. Could you please tell me how to realize such feature? (there are also detailed code about this which I put on stackoverflow

Log in to reply