Is it possible to auto add dashes to PyQt5 Line Edit while the user enters the data, for example if the user wants to enter 123456789012345
, while the user enters it should be entered like 12345-67890-12345
. Also if the user enters -
at the right position it should be accepted in. This was fairly achievable in tkinter
, using re
(question here), but I think it might be able to do the same with Qt
too.
if __name__ == '__main__':
app = QApplication(sys.argv)
le = QLineEdit()
le.show()
sys.exit(app.exec_())
Ps: I have designed the GUI inside of Qt Designer.
inputMask : QString
This property holds the validation input mask.
More 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_())