PyQt QLineEdit 与 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.
相关文章