Search code examples
c++qtkeypresskey-eventsqkeyevent

Qt sending keyPressEvent


I want to append chars to QLineEdit by sending KeyEvent. I'm using code like this:

ui.myEdit->setFocus();
for(size_t i = 0; i < 10; ++i) {
   QKeyEvent keyPressed(QKeyEvent::KeyPress, 'a', Qt::NoModifier);
   QWidget::keyPressEvent(&keyPressed); // or
   //QApplication::sendEvent(QApplication::focusWidget(), &keyPressed);
}

Why there is no change in myEdit?


Solution

  • You can change the change the text of QLineEdit simply by :

    ui->myEdit->setText(ui->myEdit->text().append("a"));
    

    But if you really want to change it by sending QKeyEvent you can try this :

    QKeyEvent * eve1 = new QKeyEvent (QEvent::KeyPress,Qt::Key_A,Qt::NoModifier,"a");
    QKeyEvent * eve2 = new QKeyEvent (QEvent::KeyRelease,Qt::Key_A,Qt::NoModifier,"a");
    
    qApp->postEvent((QObject*)ui->myEdit,(QEvent *)eve1);
    qApp->postEvent((QObject*)ui->myEdit,(QEvent *)eve2);