Important: Please read the Qt Code of Conduct -

How to press key from keyboard automatically with Qt

  • Hello everyone,

    I have a simple question.How can i able to press key automatically with qt program(for example enter or tab key)

    I investigated several examples that consist of key events.But unfortuantely they are just checking pressed key on the keyboard.

    like this one ;

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


    I think above example checks if the tab key is pressed by user.But I would like to write a code that press a specified key (I will choose )automatically by program from keyboard.

    Simply I don't want to check pressed key, I want to press a key automatically with program

    Could you please write me an example for this operation.

    Thank you in advance.

  • Lifetime Qt Champion

  • QKeyEvent * eve1 = new QKeyEvent (QEvent::KeyPress,Qt::Key_CapsLock,Qt::NoModifier,"a");
    QKeyEvent * eve2 = new QKeyEvent (QEvent::KeyRelease,Qt::Key_CapsLock,Qt::NoModifier,"a");
        QString qstr = QKeySequence(eve2->key()).toString();
        QMessageBox::information(this,"Error","pressed key ");}

    I wrote above code according to given example, but unfortunately it does not press to capslock key automatically.It shows capslock string in line edit.Bu unfortunately it does not activate the capslock from keyboard.

    Is there anything wrong?

  • Lifetime Qt Champion

    @esconda Well, you cannot do this with Qt. The example shows how to simulate key presses in your app - you can't do "real" key presses this way. Maybe there is something in OS APIs (Windows/Linux/MacOS).

  • @esconda you may want to rely to some OS specific code like the one proposed here.

Log in to reply