#!/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()
如何使用 QIntValidator 在 QlineEdit 中阻止逗号?逗号不是有效的 Python 数字,并会引发此错误 ValueError: invalidliteral for int() with base 10: '1,111'
验证器允许您输入 1,1,1,1,1,1,并在您离开小部件时将其转换为 111,111。
JT
QIntValidator 默认使用千个 Locale 来解释其他值,以增强用户输入大量数字时的可读性。这解释了为什么 1111 变成 1,111,通常是为了人类可读性而不是为了执行计算。了解更多关于QLocales。
要更改此设置,您必须将其设置为另一个语言环境,例如 C 语言环境,它会从输入中删除所有逗号和非整数,使其适合执行计算。
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)