简体   繁体   English

带有 QValidator 的 PyQt QLineEdit

[英]PyQt QLineEdit with QValidator

I have a QLineEdit in my project.我的项目中有一个 QLineEdit。 I want to use the QValidation on lineEdit.我想在 lineEdit 上使用 QValidation。

#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)

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.并且范围不起作用!我可以输入 100500 或 -100500,但我想要,该用户只能输入范围内的数字。

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 .默认情况下,验证器不会阻止输入范围之外的值,并且如果输入的值是Invalid 或 Intermediate ,它也不会阻止用户离开行编辑。

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 itseditingFinished or returnPressed signals, and its hasAcceptableInput method will return False .但是,它确实让您有机会以编程方式拒绝输入,因为只要当前值不可接受,行编辑就不会发出它的editFinishedreturnPressed信号,并且它的hasAcceptableInput方法将返回False In addition, if you subclass the validator, you can reimplement its fixup method to control the values that are entered.此外,如果您对验证器进行子类化,则可以重新实现其修复方法来控制输入的值。

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.然而,正如已经提出的那样,一个更好/更简单的解决方案是使用QDoubleSpinBox ,因为它会自动清理输入并提供更用户友好的界面。

As an alternative you could use a QDoubleSpinBox .作为替代方案,您可以使用QDoubleSpinBox

  • has validator build in已内置验证器
  • prevents invalid input while typing输入时防止无效输入
  • has build-in setRange()有内置的 setRange()
  • and adds a little handle to change the value for more mouse oriented users.并添加了一个小句柄来更改更多面向鼠标的用户的值。

Probably you are expecting something what should not happen.可能您正在期待不应该发生的事情。
In general when you have validator you should be able to type something in intermediate state what doesn't exactly meet limitation.一般来说,当你有验证器时,你应该能够在中间状态输入一些不完全符合限制的东西。 But this should be fixed, when editor looses focus.但这应该是固定的,当编辑器失去焦点时。

Why?为什么? Imagine you have 84 an you want correct this to -8.4 .想象一下,您有84并且您希望将其更正为-8.4 Many people will do this like that: add minus so now you have -84 which is not acceptable then add dot.很多人会这样做:加减号,所以现在你有-84 ,这是不可接受的,然后加点。 If validator fixes this immediately it would be annoying for user.如果验证器立即修复此问题,那么用户会很烦。

So bottom line does this "problem" happen when editor looses focus?那么当编辑器失去焦点时,这个“问题”是否会发生?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM