問題描述
我的項目中有一個 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.
這篇關于PyQt QLineEdit 與 QValidator的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!