Search code examples
pythonpyqtpyqt4qlineedit

PyQt auto-space qlineedit characters


Am having a qlineedit where a user types a verification code. I want to be able to space these numbers automatically every after 5 characters just like it is when activating windows where dashes are automatically added. For example

12345 67890 12345 67890

Solution

  • If the number of digits is fixed the best option is to use setInputMask(), in your case:

    if __name__ == '__main__':
        app = QApplication(sys.argv)
        le = QLineEdit()
        le.setInputMask(("ddddd "*4)[:-1])
        le.show()
        sys.exit(app.exec_())
    

    In the case that the number of lines is variable it is better to use the textChanged signal and to add it whenever it is necessary, besides so that it is possible to write we establish a QValidator as I show next.

    class LineEdit(QLineEdit):
        def  __init__(self, *args, **kwargs):
            QLineEdit.__init__(self, *args, **kwargs)
            self.textChanged.connect(self.onTextChanged)
            self.setValidator(QRegExpValidator(QRegExp("(\\d+)")))
    
        def onTextChanged(self, text):
            if len(text) % 6 == 5:
                self.setText(self.text()+" ")
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        le = LineEdit()
        le.show()
        sys.exit(app.exec_())