Python 如何在pyqt中限制QLineEdit中的用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15829782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to restrict user input in QLineEdit in pyqt
提问by Rao
I have a QLineEditand i want to restrict QLineEditto accept only integers. It should work like inputmask. But I dont want to use inputmask, because if user clicks on QLineEditcursor will be at the position where mouse was clicked. and user need to navigate to 0 position and type what eve he wants.
我有一个QLineEdit,我想限制QLineEdit为只接受整数。它应该像输入掩码一样工作。但我不想使用inputmask,因为如果用户点击QLineEdit光标将在鼠标点击的位置。并且用户需要导航到 0 位置并输入他想要的前夕。
Is there any alternate for this.
是否有任何替代方案。
回答by scottydelta
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 validatorsto validate input strings.
您还可以使用验证器来验证输入字符串。
回答by Fe3back
you can use QValidator it works like:
您可以使用 QValidator 它的工作原理如下:
#To allow only int
self.onlyInt = QIntValidator()
self.LineEdit.setValidator(self.onlyInt)

