PyQt: QLineEdit input mask for only Integer or onl

2020-04-19 05:37发布

问题:

These are the 2 questions(both can be solved by InputMask?)

  1. I want to restrict the user input to 16 characters only
  2. In a field like 'Age/ID', I would like the user's input to be integer only, if the user enters a string it must not be accepted or the user must not be able to type in a string in the first place.

I'm not sure how I can implement the first part in real-time,i.e., the user types a max of 16, nothing beyond 16 appears.

This is my code(not working) for the 2nd part of the question:

self.onlyInt = QIntValidator()
self.lineEdit_15.setValidator(self.onlyInt)
det15=str(self.lineEdit_15.text())
list_val.append(det15)

回答1:

To solve the first question we only have to establish a maximum size:

self.lineedit_15.setMaxLength(16)

In contrast the second QIntValidator question only works up to a maximum equal to 2147483647 since it is the maximum integer: 2**31-1, The solution is to use regular expressions:

rx = QRegExp("\d+")
self.lineedit_15.setValidator(QRegExpValidator(rx))