I use QDoubleValidator in my pyqt5 program but it doesn't seem to work
Asked Answered
C

1

5

I make a QWidget object in which there are some lineEdits and I intend to add some constraints to them, so I implement QDoubleValidator objects. Following is the related part in my code.

self.lineEdit_taxRate= QLineEdit()
self.lineEdit_taxRate.setValidator(QDoubleValidator(0.0, 100.0, 6))

But when I run the program, I find out I can still input number like 123165.15641. It seems the validator makes no difference.

I wonder if which step I missed or the validator will trigger some signal.

The lineEdit

Crannog answered 18/2, 2019 at 5:51 Comment(0)
D
7

By default QDoubleValidator uses the ScientificNotation notation, and in that notation 123165.15641 is a possible valid value since it can be converted to 123165.15641E-100 and that is a number that is between 0 and 100. In this case the solution is to establish that it is used the standard notation:

from PyQt5 import QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.lineEdit_taxRate= QtWidgets.QLineEdit()
        self.lineEdit_taxRate.setValidator(
            QtGui.QDoubleValidator(
                0.0, # bottom
                100.0, # top
                6, # decimals 
                notation=QtGui.QDoubleValidator.StandardNotation
            )
        )
        self.setCentralWidget(self.lineEdit_taxRate)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
Decrepitude answered 18/2, 2019 at 6:10 Comment(1)
here we have set the top value to 100 but we can still enter up to 999. why is that?Pentobarbital

© 2022 - 2024 — McMap. All rights reserved.