Search code examples
pythonpyqtfocuspysideqlineedit

PyQt QLineEdit defocus when enter key pressed


import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def pressenter():
   print ("Enter pressed")
def window():
   app = QApplication(sys.argv)
   win = QWidget()

   editbox = QLineEdit()
   editbox.setValidator(QDoubleValidator(0.99,99.99,2))

   eform  = QFormLayout()
   eform.addRow("Enter text: ",editbox)

   editbox.editingFinished.connect(pressenter)
   win.setLayout(eform)
   win.setWindowTitle("My Test Window")
   win.show()

   sys.exit(app.exec_())
if __name__ == '__main__':
   window()

I have simple edit box and I want my cursor to exit edit box when I press enter key so I know my input was accepted. This means that when I want to edit again I specifically need to select edit box again. I tried to search this around but I am not natural English speaker or whatsoever, maybe that's my problem but I cannot find good answer.

There are 2 problems I currently notice: Validator, which I need, is preventing enter key press, another one is that pressenter() function should probably do something but I don't know what with focus methods.


Solution

  • You can set the focus to the main window: (The focus is only switched when your input is valid, is that the behaviour you want?)

    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    def pressenter(win):
       win.setFocus()
    
    def window():
       app = QApplication(sys.argv)
       win = QWidget()
    
       editbox = QLineEdit()
       editbox.setValidator(QDoubleValidator(0.99,99.99,2))
    
       eform  = QFormLayout()
       eform.addRow("Enter text: ",editbox)
    
       editbox.editingFinished.connect(lambda: pressenter(win))
       win.setLayout(eform)
       win.setWindowTitle("My Test Window")
       win.show()
    
       sys.exit(app.exec_())
    if __name__ == '__main__':
       window()
    

    You could also validate in the pressenter function and reset the editbox if the input is not accepted:

    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    def pressenter(win, editbox):
        val = QDoubleValidator(0.99,99.99,2)
        if val.validate(editbox.text(),0)[0] == QValidator.Acceptable:
            win.setFocus()
        else:
            editbox.setText('')
    
    def window():
       app = QApplication(sys.argv)
       win = QWidget()
    
       editbox = QLineEdit()
    
       eform  = QFormLayout()
       eform.addRow("Enter text: ", editbox)
    
       editbox.editingFinished.connect(lambda: pressenter(win, editbox))
       win.setLayout(eform)
       win.setWindowTitle("My Test Window")
       win.show()
    
       sys.exit(app.exec_())
    if __name__ == '__main__':
       window()