How to restrict user input in QLineEdit in pyqt

淺唱寂寞╮ 提交于 2019-12-03 17:20:24

问题


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.


回答1:


you can use QValidator it works like:

#To allow only int
self.onlyInt = QIntValidator()
self.LineEdit.setValidator(self.onlyInt)



回答2:


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.



来源:https://stackoverflow.com/questions/15829782/how-to-restrict-user-input-in-qlineedit-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!