QKeyPress - 在Qt中模拟按键

QKeyPress - Simulating key press in Qt

本文关键字:模拟 Qt QKeyPress      更新时间:2023-10-16

如何在Qt中模拟用户交互(按键事件(?

我尝试了相同的方法,但无法写在行编辑小部件上

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

交互

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

也没有成功。

我也尝试了以下内容,但没有得到任何结果。

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";
}

请告诉我我错过了什么。

问候 萨彦

在链接中,您指示输入了输入,因此文本不是必需的,但是如果要发送信件,则必须传递该参数:

ui->lineEdit->setFocus();
QKeyEvent *key_press = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_X, Qt::NoModifier, "X");
//                                                                          text ─────┘
QApplication::sendEvent(ui->lineEdit, key_press);