QlineEdit 中的 PyQt5 块逗号

PyQt5 Block Comma in QlineEdit

提问人:jthornton 提问时间:11/12/2023 更新时间:11/13/2023 访问量:36

问:

#!/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: invalid literal for int() with base 10: '1,111'

验证器允许您输入 1,1,1,1,1,1,1,1,1,并在您离开小部件时将其转换为 111,111。

JT公司

python linux pyqt5 qlineedit

评论

0赞 musicamante 11/13/2023
另一种方法是使用 QSpinBox,最终隐藏箭头(请参见 buttonSymbols 属性)。
0赞 jthornton 11/13/2023
我已经想出了如何使QSpinBox看起来像QLineEdit,但有一个例外。我无法弄清楚在单击QSpinBox时如何选择默认的0,就像在QSpinBox中按Tab键时发生的情况一样。我的应用程序中有 >1600 个小部件,因此设置 Tab 键顺序是疯狂的。

答:

0赞 Raphael Djangmah 11/13/2023 #1

默认情况下,QIntValidator 使用 1000 个 Locale 来解释 other 中的值,以增强用户输入大量数字时的可读性。这就解释了为什么 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)

评论

0赞 jthornton 11/13/2023
非常感谢您提供的信息。有趣的是,您仍然可以输入 1,1,1,1,1,1,但是当您将焦点移动到另一个小部件时,它会变为 11111。