KeyPressEvent does not detect key 0

0

I'm trying to capture the keys I press within QLineEdit , but the keyPressEvent() method does not return any results when I press any number or letter it just seems to react with key_Return :

This is the sample code:

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLineEdit
from PyQt5 import Qt, QtCore


class Principal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.line = QLineEdit(self)

    def keyPressEvent(self,event):
        if event.key() == QtCore.Qt.Key_0: **# No detecta la tecla 0**
            print("pressed_0")
        elif event.key() == QtCore.Qt.Key_Return:
            print("pressed_return")
        event.accept()


app = QApplication([])
p = Principal()
p.show()
p.resize(600,400)
app.exec_()
    
asked by Revsky01 21.03.2018 в 21:24
source

1 answer

1

You are trying to capture the event from the instance of your main window, but it never spreads, it is "consumed" by QLineEdit . If you want to capture the keys when they are clicked inside the QLineEdit you can use QObject.eventFilter :

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLineEdit
from PyQt5 import Qt, QtCore


class Principal(QMainWindow):
    def __init__(self):
        super(Principal, self).__init__()

        self.line = QLineEdit(self)
        self.line.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and obj is self.line:
            if event.key() == QtCore.Qt.Key_0:
                print("pressed_0")
            elif event.key() == QtCore.Qt.Key_Return:
                print("pressed_return") 
        return super(Principal, self).eventFilter(obj, event)



app = QApplication([])
p = Principal()
p.show()
p.resize(600,400)
app.exec_()

return super(Principal, self).eventFilter(obj, event) allows propagating the event to the parent, if you want that event not to propagate (for example, detect the event when pressing the 0 key but it does not propagate, so the 0 will not be entered in the QLineEdit ) you must return True from the eventFilter method when the event is captured:

if event.key() == QtCore.Qt.Key_0:
    print("pressed_0")
    return True
    
answered by 21.03.2018 / 22:53
source