Ilya Glushchenko
Ilya Glushchenko

Reputation: 327

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?

Upvotes: 2

Views: 6287

Answers (2)

Malachi Bazar
Malachi Bazar

Reputation: 1823

I had the same problem.

Pyautogui is very good for this and it is stupid simple.

import pyautogui
pyautogui.typewrite("the stuff")

Or if you want to actually simulate pressing a literal keypress use:

import pyautogui
pyautogui.keypressDown("the stuff")
pyautogui.keypressUp("the stuff")

Here's the documentation: https://pyautogui.readthedocs.org/en/latest/

Hope this helps.

Upvotes: 3

Nicolas Holthaus
Nicolas Holthaus

Reputation: 8273

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

Upvotes: 3

Related Questions