如何更改 lineEdit 的 QValidator 行为:

How to change behavior of QValidator for lineEdit:

我已经为我的 lineEdit 设置了一个 QRegExpValidator 来接受格式为 111.111 或 111,111 或 111 的数字。

当用户输入“111”时 - 验证器的状态为中级。但是当用户按下回车键或 lineEdit 失去焦点时(假设用户输入错误) - lineEdit 中的文本 'freezes'。我希望“111”在这种情况下会更改为可接受的值,例如更改为“111”。

我该怎么做?我想这与 QValidator.fixup() 函数或整个 QValidator 的子类化有关。

import sys
from PyQt5 import QtWidgets, QtCore,  QtGui


class Mainwindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("window")
        self.lineEdit = QtWidgets.QLineEdit()
        self.lineEdit_2 = QtWidgets.QLineEdit()
        self.layout =  QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.lineEdit)
        self.layout.addWidget(self.lineEdit_2)
        self.setLayout(self.layout)

        regexp = QtCore.QRegExp("^\d+[\.,]\d+$|^\d+$") #accepts numbers in format 111.111 or 111,111 or 111
        validator = QtGui.QRegExpValidator(regexp)

        self.lineEdit.setValidator(validator)
        

        self.lineEdit.returnPressed.connect(lambda: print(self.lineEdit.text()))


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    application = Mainwindow()
    application.show()


    sys.exit(app.exec())

是的,您需要覆盖 fixup() 方法。

请注意,在 C++ 中,input 参数是可修改的,这就是为什么根据 documentation 似乎 return 什么都没有(“void”)。
在 PyQt 中这是不可能的,因为字符串是不可变类型,所以 return 签名不同于它的 C++ 签名(参见 release notes about QValidator),因此它实际上可以 return 一个字符串。

class Validator(QtGui.QRegExpValidator):
    def fixup(self, input):
        while input.endswith(('.', ',')):
            input = input.rstrip(',')
            input = input.rstrip('.')
        return input


class Mainwindow(QtWidgets.QWidget):
    def __init__(self):
        # ...
        validator = Validator(regexp)
        # ...