简体   繁体   中英

QKeyPress - Simulating key press in Qt

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM