自动向 Line Edit PyQt5 添加破折号

问题描述

是否可以在用户输入数据时自动向 PyQt5 Line Edit 添加破折号,例如,如果用户想输入 123456789012345,而用户输入时应该像 12345-67890-12345 这样输入。此外,如果用户在正确的位置输入 -,它应该被接受。这在 tkinter 中是可以实现的,使用 re(question here),但我认为它也可以对 Qt 做同样的事情。

if __name__ == '__main__':
    app = QApplication(sys.argv)
    le = QLineEdit()
    le.show()
    sys.exit(app.exec_())

Ps:我在 Qt Designer 中设计了 GUI。

解决方法

输入掩码:QString

此属性保存验证输入掩码。

更多https://doc.qt.io/qt-5/qlineedit.html#inputMask-prop

import sys
from PyQt5 import QtCore,QtGui,QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(centralWidget)

        self.lineEdit = QtWidgets.QLineEdit()
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit.editingFinished.connect(self.editingFinished)
        
        self.lineEdit.setInputMask("999-9999999;.")                                 # +++
        
        grid = QtWidgets.QGridLayout(centralWidget)
        grid.addWidget(self.lineEdit) 
        
    def editingFinished(self):
        print(f"{self.lineEdit.text()} -> {self.lineEdit.text().replace('-','')}")
        

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    app.setFont(QtGui.QFont("Times",22,QtGui.QFont.Bold))
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

enter image description here