如何在Qt5中伪装键盘事件到小部件

时间:2014-06-21 19:33:33

标签: qt5 keyboard-events

我为自助服务终端应用程序制作了一个自定义虚拟键盘​​小部件,现在我想要它生成假键盘事件并将它们提供给选择的QLineEdit。

我执行以下操作:

// target is the QWidget to receive the events
// k is the Qt::Key (keycode) I want to send (Testing with an 'A')
Qt::Key k=Qt::Key_A;
if(0!=target){
    //According to docs this will be freed once posted
    QKeyEvent * press=new QKeyEvent(QKeyEvent::KeyPress, (int )k,0);
    QKeyEvent * release=new QKeyEvent(QKeyEvent::KeyRelease, (int )k,0);
    //Give the target focus just to be sure it is available for input
    target->setFocus();
    //Post the events (queue up and let the target consume them when the eventloop gets around to the target)
    QCoreApplication::postEvent ( target, press) ;
    QCoreApplication::postEvent ( target, release) ;
}

我看到目标小部件获得了焦点,但是没有像我期望的那样在输入字段中输入字母。我究竟做错了什么?哪些假设是错误的?

PS:我知道这可以通过使用现有的虚拟键盘或至少使用平台界面来解决,如this post中所述。在我们的方法中,我们决定将kayboard构建到应用程序中,以获得对UX和键盘设计的完全控制。

谢谢!

1 个答案:

答案 0 :(得分:2)

由于没有人加强,我会尝试提供一些关闭。

事实证明,Qt5附带了一个名为testlib的测试工具库。它有各种各样的好东西,可以方便地创建,管理和运行Qt应用程序的单元测试。在这些设施中,有一组用于发送虚假事件的功能,例如伪造文本输入,鼠标点击等。它非常全面,涵盖了许多用例。由于Qt开发人员在内部使用它来测试Qt本身,因此它也是经过生产验证的代码。

我只是从那里复制了我需要的东西。