23

I have a QLineEdit and i want to restrict QLineEdit to accept only integers. It should work like inputmask. But I dont want to use inputmask, because if user clicks on QLineEdit cursor will be at the position where mouse was clicked. and user need to navigate to 0 position and type what eve he wants.

Is there any alternate for this.

Anthon
  • 69,918
  • 32
  • 186
  • 246
Rao
  • 2,902
  • 14
  • 52
  • 70

2 Answers2

55

you can use QValidator. It works like:

# from PyQt5.QtGui import QIntValidator
# from PyQt6.QtGui import QIntValidator

# allow only integers
onlyInt = QIntValidator()
onlyInt.setRange(0, 4)
lineEdit.setValidator(onlyInt)
DomTomCat
  • 8,189
  • 1
  • 49
  • 64
Fe3back
  • 924
  • 7
  • 15
9

you can use exception handling for validating this:

number = self.ui.number_lineEdit.text()
try:
    number = int(number)
except Exception:
    QtGui.QMessageBox.about(self, 'Error','Input can only be a number')
    pass

you can also use validators to validate input strings.

scottydelta
  • 1,786
  • 4
  • 19
  • 39
  • i heard about `validators`, but did not get find a correct example on how to set it to `QLineEdit`. Mean while i will try your approch. I think Validators are the good options for professional approach. – Rao Apr 06 '13 at 11:42
  • 1
    try learning from this question here http://stackoverflow.com/questions/5770441/checking-qvalidators-state – scottydelta Apr 07 '13 at 02:49
  • 3
    A good exemple of how to use validators is here: http://snorf.net/blog/2014/08/09/using-qvalidator-in-pyqt4-to-validate-user-input/ – maurobio Apr 18 '15 at 14:06
  • 3
    @maurobio - linkupdate: https://snorfalorpagus.net/blog/2014/08/09/validating-user-input-in-pyqt4-using-qvalidator – ZF007 Nov 26 '17 at 12:38