Decimal seperator: QtGui.QDoubleValidator

Heads up! You've already completed this tutorial.

Alexis_Labuschagne | 2021-01-03 14:40:21 UTC | #1

RE Using "QDoubleValidator(double bottom , double top , int decimals , QObject * parent = nullptr)"

Source code: self.InputLineEdit.setValidator(QtGui.QDoubleValidator(0.1,99.9.0,2))

I get a comma allowed for the decimal separator where I need a point in the QLineEdit widget. Any advice how to force a point decimal separator?


martin | 2021-01-10 18:56:22 UTC | #2

Hi @Alexis_Labuschagne The decimal separator is handled through the locale which defines how numbers are displayed/handled for localization purposes.

The comma separator is probably following your system defaults, but you can override it as follows. This creates a custom locale (using United States, which uses the decimal point for decimals) and applies it to the field. Note that the comma is still allowed, since this is a decimal group operator.

python
from PyQt5.QtWidgets import QApplication, QLineEdit
from PyQt5.QtGui import QDoubleValidator
from PyQt5.QtCore import QLocale

app = QApplication([])

lineedit = QLineEdit()
lineedit.show()
validator = QDoubleValidator(0.1,9990,2)

locale = QLocale(QLocale.English, QLocale.UnitedStates)

validator.setLocale(locale)
validator.setNotation(QDoubleValidator.StandardNotation)
lineedit.setValidator(validator)

lineedit.textChanged.connect(print)

lineedit.show()

app.exec_()

The line below is invalid Python, since Python syntax only allows numbers to have a single decimal point in them (and no commas).

python
self.InputLineEdit.setValidator(QtGui.QDoubleValidator(0.1,99.9.0,2))

If you want to use alternative grouping in the number (e.g. like an IP address) with multiple decimal points, you can implement your own validator by subclassing QValidator. Let me know if that's what you're looking for.


Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt5
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

Decimal seperator: QtGui.QDoubleValidator was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.