0

我写了这个简单的 QT 主窗口,只有当我将 QString 参数传递给 QKeyEvent 时,它才会打印密钥,我希望即使没有 QString 参数也能打印密钥?

下面代码中的第 1 部分似乎不起作用(我没有在 QLineEdit 字段中打印密钥;而第 2 部分有效并且打印了“1”!这是正常行为吗?事件在第一次发布时会发生什么情况部分代码?

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! 

}
4

1 回答 1

1

并非所有的键事件都有文本表示(删除、光标移动、快捷方式……)。对于那些拥有它的人,QKeyEvent该类将其存储在其文本中。您必须提供该文本,否则它是“无文本”事件。

QLineEdit只会添加文本,而不是从事件类型中推断出来(可以看到这里

于 2018-01-10T17:02:17.707 回答