带有 QValidator 的 PyQt QLineEdit [英] PyQt QLineEdit with QValidator
问题描述
我的项目中有一个 QLineEdit.我想在 lineEdit 上使用 QValidation.
I have a QLineEdit in my project. I want to use the QValidation on lineEdit.
#Create lineEdit
itemValue = QtWidgets.QLineEdit()
#Create валидатор
objValidator = QtGui.QDoubleValidator(self)
#setup range
objValidator.setRange(-10.0, 100.0, 5)
#lineEdit with validation
itemValue.setValidator(objValidator)
但效果不佳.我可以输入我想要的内容,但符号除外.并且范围不起作用!我可以输入 100500 或 -100500,但我想要,该用户只能输入范围内的数字.
But it doesn't work well.I can type what i want, except symbols. And range doesn't work!I can type 100500 or -100500, but i want, that user can enter numbers only in range.
我应该如何使用范围?我需要帮助:)
How i should use range? I need help:)
感谢您的帮助,伙计们!
Thanks for your help, guys!
推荐答案
默认情况下,验证器不会阻止输入范围外的值,并且不会阻止用户在输入值时离开行编辑是无效或中级.
By default, a validator will not prevent values outside the range from being entered, and it won't prevent the user leaving the line-edit if the entered value is Invalid or Intermediate.
但是,它确实让您有机会以编程方式拒绝输入,因为只要当前值不可接受,行编辑就不会发出它的 editingFinished 或 returnPressed 信号及其hasAcceptableInput 方法将返回 False
.此外,如果您对验证器进行子类化,则可以重新实现其fixup 控制输入值的方法.
However, it does give you an opportunity to reject the input programmatically, because whenever the current value is unacceptable, the line-edit won't emit its editingFinished or returnPressed signals, and its hasAcceptableInput method will return False
. In addition, if you subclass the validator, you can reimplement its fixup method to control the values that are entered.
然而,正如已经提出的那样,一个更好/更简单的解决方案是使用 QDoubleSpinBox
,因为它会自动清理输入并提供更加用户友好的界面.
However, as has been suggested already, a far better/simpler solution is to use a QDoubleSpinBox
, since it cleans up the input automatically and provides a more user-friendly interface.
这篇关于带有 QValidator 的 PyQt QLineEdit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!