I have created a form using PyQT5 using python, in the form I getting value from user through QLineEdit.
My problem is that user should not leave any of the field empty in the form.
How to avoid empty Lineedit?
I have created a form using PyQT5 using python, in the form I getting value from user through QLineEdit.
My problem is that user should not leave any of the field empty in the form.
How to avoid empty Lineedit?
A simple solution is to use a custom QValidator:
from PyQt5 import QtGui, QtWidgets
class NotEmptyValidator(QtGui.QValidator):
def validate(self, text, pos):
state = QtGui.QIntValidator.Acceptable if bool(text) else QtGui.QIntValidator.Invalid
return state, text, pos
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QLineEdit("Hello World")
validator = NotEmptyValidator(w)
w.setValidator(validator)
w.show()
sys.exit(app.exec_())
Extending on eyllanesc's answer:
If you want to make it possible that the user empties the field temporarily (e.g. to remove all text and write completely new content), you should not return an empty field as Invalid
but rather as Intermediate
. If there is one letter left but an empty QLineEdit
would be Invalid
, then the user may be blocked from removing the last letter and would instead have to do some kind of workaround. Also, the code below strips possible whitespace before checking for emptiness.
class NotEmptyValidator(QValidator):
def validate(self, text: str, pos):
if bool(text.strip()):
state = QValidator.Acceptable
else:
state = QValidator.Intermediate # so that field can be made empty temporarily
return state, text, pos