keyPressEvent() with QCalendarWidget

John F Sturtz john at sturtz.org
Fri Nov 4 20:54:34 GMT 2022


Hi.  Some time ago, I posted quite a few questions to this forum.  Folks 
were greatly helpful, and I thank you all.

This is sort of a silly, frivolous question.  In that it wouldn't really 
be a big deal if I couldn't do what I was trying to do.  Mostly, it just 
really puzzles me.  And it bugs me when I don't understand.

I've got an app that uses the QCalendarWidget, and I got it in my head 
to redefine some keys.  So I subclassed QCalendarWidget and defined a 
custom keyPressEvent().  I can see that some key events are received by 
the custom method.  But many not -- including the Space character (the 
one I originally intended to redefine), and all the alphabetic keys.

Here's a small example to demonstrate:

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

class Calendar(QCalendarWidget):

     def __init__(self, parent=None):
         super().__init__(parent)

     def keyPressEvent(self, event):
         key = event.key()
         mod = int(event.modifiers())
         handled = False

         print(key, mod)

         if key == Qt.Key_Space:
             print('[space]')
             handled = True

         if not handled:
             super().keyPressEvent(event)


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

app.exec()

(File also attached).

If I run this, the first print() statement executes if I hit (for 
example) the Escape or Delete key.  But if I hit the Space key, all that 
happens is that the widget displays a tooltip showing the currently 
selected date.

How can this even happen?  How is this widget stopping my custom 
keyPressEvent() method from receiving some keystrokes?  And more to the 
point, I suppose:  Is there a way I can make it otherwise?

Thanks again!

/John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20221104/82bc8607/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.py
Type: text/x-python
Size: 591 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20221104/82bc8607/attachment.py>


More information about the PyQt mailing list