QLineEdit
has the signal returnPressed
that is issued when you press enter.
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic
class Primera(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
uic.loadUi("Inicio.ui",self)
self.l_codigo.returnPressed.connect(self.edit.setFocus)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
p = Primera()
p.show()
sys.exit(app.exec_())
On the other hand when using keyPressEvent you are overwriting the event of Primera
, that has nothing to do with the QLineEdit, if you want to use eventFilter (only use this method if the appropriate signal does not exist) you should do it in the following way :
from PyQt5.QtCore import QEvent, Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic
class Primera(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
uic.loadUi("Inicio.ui",self)
self.l_codigo.installEventFilter(self)
def eventFilter(self,obj,event):
if obj is self.l_codigo and event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Return:
self.edit.setFocus()
return QMainWindow.eventFilter(self,obj,event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
p = Primera()
p.show()
sys.exit(app.exec_())
As you realize, the second method is less elegant, more extensive.
If we overwrite keyPressEvent () correctly, it should be as follows:
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic
class Primera(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
uic.loadUi("Inicio.ui",self)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
print("event")
return QMainWindow.keyPressEvent(self, event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
p = Primera()
p.show()
sys.exit(app.exec_())
But the problem is that it will be launched for all the widgets that are children of Principal