PyQt auto-space qlineedit characters

荒凉一梦 提交于 2021-01-28 01:31:59

问题


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

回答1:


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_())


来源:https://stackoverflow.com/questions/46069642/pyqt-auto-space-qlineedit-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!