Qt sending keyPressEvent

user3369485 picture user3369485 · Jun 20, 2014 · Viewed 10.4k times · Source

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?

Answer

Nejat picture Nejat · Jun 20, 2014

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