PyQt:QValidator 函数定义

alp*_*ric 5 python pyqt

我目前正在使用一种相当残酷的方法来轻松获得 QValidator 可以提供的内容。在这个小部件上找到一个简单的信息是相当困难的。下面的代码是从另一篇文章复制/粘贴的(经过一些小的编辑)。它创建一个对话框,其中单行编辑连接到 ValidStringLength QValidator,强制字符串大小为 0 < 长度 < 5。我想了解应该将字符串清理“可执行”函数放置在哪里:在 fixup() 方法内?请解释一下 QValidator() 背后的逻辑。


   from PyQt4 import QtCore, QtGui
    class ValidStringLength(QtGui.QValidator):
        def __init__(self, min, max, parent):
            QtGui.QValidator.__init__(self, parent)

            self.min = min
            self.max = max

        def validate(self, s, pos):
            print 'validate(): ', type(s), type(pos), s, pos

            if self.max > -1 and len(s) > self.max:
                return (QtGui.QValidator.Invalid, pos)

            if self.min > -1 and len(s) < self.min:
                return (QtGui.QValidator.Intermediate, pos)

            return (QtGui.QValidator.Acceptable, pos)

        def fixup(self, s):
            pass


    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)

            self.editLine = QtGui.QLineEdit(self)
            self.validator = ValidStringLength(0,5,self)

            self.editLine.setValidator(self.validator)

            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.editLine)

    if __name__ == '__main__':

        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 300, 500, 100)
        window.show()
        sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

seb*_*ian 1

来自 Qt 文档:

fixup() 是为验证器提供的,可以修复一些用户错误。默认实现不执行任何操作。例如,如果用户按 Enter(或 Return)并且内容当前无效,则 QLineEdit 将调用 fixup()。这使得 fixup() 函数有机会执行一些魔法,使无效字符串变得可接受。

http://qt-project.org/doc/qt-4.8/qvalidator.html

所以是的,如果您的“字符串清理”是尝试纠正用户的输入,那么fixup应该是执行此操作的正确位置。

编辑:

这应该将前四个字符大写:

def validate(self, s, pos):
    print 'validate(): ', type(s), type(pos), s, pos

    n = min(4,s.count())
    if s.left(n).compare(s.left(n).toUpper()):
        return (QtGui.QValidator.Intermediate, pos)
    else:
        return (QtGui.QValidator.Acceptable, pos)

def fixup(self, s):
    n = min(4, s.count())
    s.replace(0, n, s.left(n).toUpper())
Run Code Online (Sandbox Code Playgroud)