3

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Shri
  • 99
  • 1
  • 1
  • 6

3 Answers3

5

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
3

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
nspo
  • 1,488
  • 16
  • 21
0

You can first convert it into text with

name = lineEdit.text()

use a if statement to detect empty value like this

if name == "":
     print("Empty")

More details here

Enos jeba
  • 72
  • 1
  • 3
  • 10