1

I have a QLineEdit for Date in mm/dd/yyyy format. I am getting input using the keyboard and not using QDateEdit because of the requirement. And when the lineEdit comes to view, it has to show to the user the current date. I need the following for the lineEdit.

  1. I need the two slashes always to be displayed and the cursor has to skip while entering or deleting.
  2. I should not allow the user to enter an invalid date i.e while entering itself the lineEdit should not get invalid numbers.
  3. I have to set the current date as the default text when the lineEdit comes to view.

For the first point, I tried using setInputMask("99/99/9999") but with this I can't set the current date using setText(). And how to use QRegExp to not to allow lineEdit get an invalid number while employing setInputMask()?

AAEM
  • 1,837
  • 2
  • 18
  • 26
jxgn
  • 741
  • 2
  • 15
  • 36

2 Answers2

1

QDateEdit will serve your purpose.

  1. use setDisplayFormat("dd/MM/yyyy").

  2. QDateEdit wont allow invalid dates

  3. You can use QDateEdit::setDate() obtained from QDateTime::currentDateTime()

techneaz
  • 998
  • 6
  • 9
1

For setting text into QLineEdit with setInputMask("99/99/9999") you should format text depending on your mask:

lineEdit.setText("{:02d}/{:02d}/{:04d}".format(m, d, y))

Alternatively, you can temporary disable InputMask, format your date without /, set it and re-enable InputMask. But make sure that number of symbols in every part is correct.

lineEdit.setInputMask("")
lineEdit.setText(date_str.replace("/", ""))
lineEdit.setInputMask("99/99/9999")
Atominick
  • 11
  • 3