keyPressEvent() with QCalendarWidget

John F Sturtz john at
Mon Nov 7 04:51:00 GMT 2022

Maurizio Berti wrote on 11/5/2022 6:09 PM:
>  [ "crossposted" as John (who I hope doesn't mind) did reply 
> privately, but I believe that this might be useful to others]
Don't mind at all.  :-)
> That said, the reason is caused by the fact that the view used in 
> QCalendarWidget is actually a private subclass (named QCalendarView) 
> which on its own overrides keyPressEvent.
> My understanding is that, since that class is not publicly declared, 
> you cannot override any of its methods, and you can only use its 
> functions by explicitly calling them (like installing the event filter).
This makes sense (from 10,000 feet; I'm not a C++ programmer).


Here's one more thing for you, or anyone else who might be interested, 
to ponder.  It seems there's one small problem with the date that the 
date edit popup initially displays.

If I call setSelectedDate() when the QCalendarWidget is first displayed 
and set the selected date to something other than today's date, that 
date will correctly show in the calendar.  But then if I hit a character 
key to display the popup, it will display today's date, not the one 
selected in the calendar.

Note that if I then click on (or arrow to) some other date in the 
calendar to select it, then display the popup, it will display the 
correct (newly-selected) date.  So it seems the popup must respond to 
the selectionChanged signal.  But evidently not the first time.  (I'm 
guessing maybe the selectionChanged signal isn't connected until after 
the popup widget is created the first time?  I spent a bit of time 
looking through the source code, but it's a little over my head ...)

This isn't really a big huge deal.  Mostly just a curiosity.  I tried 
just about everything I could think of to get around it, but couldn't 
find anything.

from PyQt5.QtWidgets import QApplication, QCalendarWidget
from PyQt5.QtCore import QDate
import sys

class Calendar(QCalendarWidget):

     def __init__(self, parent=None):


     def showEvent(self, event):

         # This sets the calendar's selected date 4 days ahead of 
today's date.
         # The calendar will correctly display it, but the first time 
you display
         # the date edit popup, it will initially display today's date, 
not the
         # date selected in the calendar.

         # I tried emitting the selectionChanged signal explicitly, but that
         # didn't work either
         # self.selectionChanged.emit()

app = QApplication(sys.argv)
window = Calendar()


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the PyQt mailing list