0

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46

1 Answers1

1

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

enter image description here

S. Nick
  • 12,879
  • 8
  • 25
  • 33
  • Did not know it was gonna be this simple. Any ways to change the insertion cursor thickness and dots there? – Delrius Euphoria Jan 19 '21 at 15:59
  • 1
    @CoolCloud remove `app.setFont(QtGui.QFont("Times", 22, QtGui.QFont.Bold))` – S. Nick Jan 19 '21 at 16:02
  • Thanks! But also I noticed that if I try to capture the empty box value, it is `'--'` could that be set to `''`? Because I am might do some evaluation if the box is empty or not later on. I think using `'--'` as definition of empty will be fine, but any other ways? – Delrius Euphoria Jan 19 '21 at 16:04
  • Just a small doubt regarding the link you included, does the same formats in the link for with python too? – Delrius Euphoria Jan 19 '21 at 18:44
  • 1
    @CoolCloud see https://doc.bccnsoft.com/docs/PyQt5/api/qlineedit.html and https://doc.qt.io/qtforpython/PySide6/QtWidgets/QLineEdit.html?highlight=inputmask#PySide6.QtWidgets.PySide6.QtWidgets.QLineEdit.setInputMask – S. Nick Jan 19 '21 at 19:13