Why keyPress Event in PyQt does not work for key Enter?
Asked Answered
B

3

6

Why, when I press Enter, does the keyPressEvent method not do what I need? It just moves the cursor to a new line.

class TextArea(QTextEdit):
    def __init__(self, parent):
        super().__init__(parent=parent)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.show()

    def SLOT_SendMsg(self):
        return lambda: self.get_and_send()

    def get_and_send(self):
        text = self.toPlainText()
        self.clear()
        get_connect(text)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Enter: 
            self.get_and_send()
        else:
            super().keyPressEvent(event)
Blossom answered 7/3, 2013 at 4:25 Comment(0)
N
9

Qt.Key_Enter is the Enter located on the keypad:

Qt::Key_Return  0x01000004   
Qt::Key_Enter   0x01000005  Typically located on the keypad.

Use:

def keyPressEvent(self, qKeyEvent):
    print(qKeyEvent.key())
    if qKeyEvent.key() == QtCore.Qt.Key_Return: 
        print('Enter pressed')
    else:
        super().keyPressEvent(qKeyEvent)
Northeaster answered 10/3, 2013 at 5:49 Comment(0)
D
0
    def keyPressEvent(self, event):
        if (event.key() == 16777220) or (event.key() == 43):  # for main keyboard and keypad

Works for my keyboard.

Despond answered 13/12, 2022 at 16:24 Comment(0)
H
0

My grain of salt to complement the answers from @warvariuc and @tCot. A bit more pythonic:

def keyPressEvent(self, qKeyEvent):
    if qKeyEvent.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): 
        pass # your code
    else:
        super().keyPressEvent(qKeyEvent)
Husband answered 8/2, 2023 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.