PyQt 自动间隔 qlineedit 字符 [英] PyQt auto-space qlineedit characters
问题描述
我有一个用户输入验证码的 qlineedit.我希望能够每隔 5 个字符自动间隔这些数字,就像在激活自动添加破折号的窗口时一样.例如
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
推荐答案
如果位数是固定的,最好的选择是使用 setInputMask()
,在你的情况下:
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_())
在行数可变的情况下,最好使用 textChanged
信号并在必要时添加它,此外,为了可以编写我们建立一个 QValidator,如下所示.
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_())
这篇关于PyQt 自动间隔 qlineedit 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!