Frage

I am currently using a quite brutal approach in getting of what QValidator would deliver with ease. Locating a simple info on this widget is quite difficult. A code below copied/pasted (after some minor editing) from another post. It creates a dialog with single lineEdit connected to ValidStringLength QValidator which enforces a string size to be 0 < length < 5. I would like to understand where should be a string-cleaning "executable" function placed: inside a fixup() method? Please explain the logic behind 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_())
War es hilfreich?

Lösung

From the Qt docs:

fixup() is provided for validators that can repair some user errors. The default implementation does nothing. QLineEdit, for example, will call fixup() if the user presses Enter (or Return) and the content is not currently valid. This allows the fixup() function the opportunity of performing some magic to make an Invalid string Acceptable.

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

So yes, if your 'string cleaning' is an attempt to correct the user's input, fixup should be the correct place to do this.

EDIT:

This should capitalize the first four characters:

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())
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top