QDateEdit with calendar signals editingFinished() when calendar popup is clicked

541 Views Asked by At

I have a QDateEdit with the calendar enabled and am trying to capture the end of editing:

the_date = QDateEdit(...)
<some more initialization>
the_date.setCalendarPopup(True)
the_date.editingFinished.connect(checkDate)
...
def checkDate():
  print ("checkDate called")

If I edit the date from the keyboard, checkDate() is called when focus leaves the widget by tabbing, hitting return, etc. But if I click on the down arrow that forces display of the calendar, checkDate() is called immediately when the calendar appears, and again when the widget loses focus. I don't want to tie to the userDateChanged because that signals on every keystroke in the edit box.

2

There are 2 best solutions below

0
On

You can save the calendar widget from the QDateTime and check if that's where focus shifted:

the_date = QDateEdit(...)
<some more initialization>
the_date.setCalendarPopup(True)
calendar = the_date.calendarWidget()
the_date.editingFinished.connect(checkDate)
...
def checkDate():
  if not calendar.hasFocus()
    # do whatever it was you wanted to do when QDateEdit finished editing
4
On

QDateEdit inherits from QDateTimeEdit, which in turn inherits from QAbstractSpinBox, which has the keyboardTracking property (enabled by default):

If keyboard tracking is disabled, the spinbox doesn't emit the valueChanged() and textChanged() signals while typing. It emits the signals later, when the return key is pressed, when keyboard focus is lost, or when other spinbox functionality is used, e.g. pressing an arrow key.

The following will provide what you need, without checking the popup focus:

    the_date.setKeyboardTracking(False)

Consider that while your solution might be correct, it's always better to check for the popup dynamically:

    if not the_date.calendarWidget().hasFocus():
        # ...