Search code examples
pythonwindowsqtpyqtkeypress

How to simulate a real keyboard's keypress in Python/PyQt?


I need to write a virtual keyboard for typing texts, I'm planning to use Python and Qt (PyQt) library for this task. problem is I don't know how to simulate KeyPress not as internal Qt event, but as simulation of a real keyboard so I could work with this keyboard as like with real one - interacting with application on my computer. I can't find anything in Qt documentation about this. So is there any way to do it through PyQt/Qt, or I need to use some Python library, and which exactly?


Solution

  • I understand that this is a PyQt question, but at the request of the OP will give a c++ example in case it helps in finding the Python solution.

    On the c++ side simulating the keyboard is done by posting keypress events to the application's event loop. These may be considered 'internal Qt events', but are the exact same interface as would be received for a physical key press. They are accomplished as follows:

    QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Enter);
    QCoreApplication::postEvent (receiver, event);
    

    Looking through the PyQt QCoreApplcation API, the postEvent function also exists, so it should be possible to do something analagous (unfortunately I can't offer an example as I'm unfamiliar with writting python scripts).