Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to convert QtCore.Qt.Key to a string

I’m capturing keyboard events for a remote desktop application by overriding the keyPressEvent() function like this:

def keyPressEvent(self, event):
    key = event.key()
    if key > 9999999999:
        print('key code too long')
        return
    self.io_soc.send(f'key {key}'.encode()

I want to simulate the keyboard event on the other computer, but the problem is that the I need to convert the key code that event.key() gives to a string because pyautogui.press() takes a string as an argument.

I didn’t find any way to get the key as a string or convert it. Please provide me with a way to do this conversion, or a way to solve this problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Ok, try this:

from PyQt5.QtCore import Qt

# Dictionary mapping Qt key codes to pyautogui string representations
KEY_MAP = {
    Qt.Key_Backspace: 'backspace',
    Qt.Key_Tab: 'tab',
    # Add mappings for other keys you need to support
    Qt.Key_Return: 'enter',
    Qt.Key_Enter: 'enter',
    Qt.Key_Escape: 'esc',
    Qt.Key_Space: 'space',
    Qt.Key_End: 'end',
    Qt.Key_Home: 'home',
    Qt.Key_Left: 'left',
    Qt.Key_Up: 'up',
    Qt.Key_Right: 'right',
    Qt.Key_Down: 'down',
    Qt.Key_Delete: 'delete',
    # ... and so on for other non-character keys
}

class RemoteDesktopWidget(QWidget):
    # ... other methods ...

    def keyPressEvent(self, event):
        key = event.key()
        if key > 9999999999:
            print('key code too long')
            return

        # Check if key is a known special key
        if key in KEY_MAP:
            key_str = KEY_MAP[key]
        else:
            # Convert to a string representation for character keys
            key_str = event.text()
        
        self.io_soc.send(f'key {key_str}'.encode())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading