简体   繁体   中英

Qt LineEdit setInputMask() with setText() and QRegExp

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 ie 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() ?

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM