I have written this simple QT mainwindow, only if I pass QString argument to the QKeyEvent, it prints the key, I expect the key to be printed even without QString argument?
section 1 in below code does not seem to work (I don't get the key printed in the QLineEdit field; while section 2 works and "1" is printed! is this normal behavior? what happens to the event when its posted in first section of the code?
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->ui->lineEdit->setFocus();
Qt::Key key = Qt::Key_1;
// 1
QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, key ,Qt::NoModifier);
QCoreApplication::postEvent(QWidget::focusWidget(), event); // Does not work! No key is set in the widget
//
//2
QKeyEvent *event2 = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, QKeySequence(key).toString());
QCoreApplication::postEvent(QWidget::focusWidget(), event2); // this one works!
}
Not all key-events have a text representation (delete, curser movement, shortcuts, ...). For those who have one, the QKeyEvent
class stores it in its text. You have to provide that text, otherwise its a "textless" event.
QLineEdit
will just add the text, and not deduce it from the event type (as can be seen here)