PyQt5 Block Comma in QlineEdit

62 views Asked by At
#!/usr/bin/env python3

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLineEdit
from PyQt5.QtWidgets import QPushButton, QVBoxLayout
from PyQt5.QtGui import  QIntValidator

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Simple Main Window")
        button = QPushButton("Press Me!")

        self.cw = QWidget()
        self.setCentralWidget(self.cw)

        layout = QVBoxLayout()
        self.cw.setLayout(layout)

        only_int = QIntValidator()
        self.num_le = QLineEdit()
        layout.addWidget(self.num_le)
        self.num_le.setValidator(only_int)

        self.button = QPushButton("Press Me!")
        layout.addWidget(self.button)
        self.button.clicked.connect(self.calc)

        self.show()

    def calc(self):
        print(int(self.num_le.text()))

app = QApplication(sys.argv)
window = MainWindow()
app.exec()

How can I block commas in a QlineEdit with QIntValidator? A comma is not a valid Python number and throws this error ValueError: invalid literal for int() with base 10: '1,111'

The validator allows you to enter 1,1,1,1,1,1 and converts that to 111,111 when you leave the widget.

JT

1

There are 1 answers

1
Raphael Djangmah On

QIntValidator by default uses the thousand Locale to interpret values in other to enhance readability when users enter large numbers. This explains why 1111 turns 1,111, usually for human readability and not for performing computation. Read more on QLocales.

To change this, you must set it to another locale such as the C locale which removes all commas and non-integers from the input, making it suitable for performing computations.

from PyQt5.QtCore import QLocale



only_int = QIntValidator()
c_locale = QLocale(QLocale.C)
only_int.setLocale(c_locale)

self.num_le = QLineEdit()
layout.addWidget(self.num_le)
self.num_le.setValidator(only_int)