Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 895
Travis Avatar asked Feb 18 '19 05:02

Travis


1 Answers

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_())
like image 149
eyllanesc Avatar answered Oct 20 '22 03:10

eyllanesc