1

How can I simulate user interaction (key press event) in Qt?

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

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

Alternately

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.

Regards, Sayan

Sayan Bera
  • 135
  • 2
  • 16

1 Answers1

4

In the link you indicate an enter is given so the text is not necessary, but in the case you want to send a letter you must pass that parameter:

ui->lineEdit->setFocus();
QKeyEvent *key_press = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_X, Qt::NoModifier, "X");
//                                                                          text ─────┘
QApplication::sendEvent(ui->lineEdit, key_press);
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • This is a sample code. I'm actually trying to simulate a Key x press on a certain openGL viewer, which has a functionality for "x" press event. I need to do the same on a button click() instead of "x" press. So, trying to simulate the same function what "x" press does in the button's clicked() slot. – Sayan Bera Oct 03 '18 at 08:25
  • Hey...i'm able to achieve the output by adding the last parameter as "x". – Sayan Bera Oct 03 '18 at 08:38