Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QCalendarWidget on year click using pyqt5

How to fire mouse click event on clicking in year option for QCalendarWidget.

encircle image

onclick of year(2012), i want to print some text using pyqt5 Can anyone help. Thanks in advance/

like image 374
Sanjiv Kumar Avatar asked Dec 03 '25 18:12

Sanjiv Kumar


1 Answers

The first thing is to obtain the QSpinBox that shows the year using findChildren, then it is to detect the mouse event but as this solution points out it is not possible so a workaround is to detect the focus event:

from PyQt5 import QtCore, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.calendar_widget = QtWidgets.QCalendarWidget()
        self.setCentralWidget(self.calendar_widget)

        self.year_spinbox = self.calendar_widget.findChild(
            QtWidgets.QSpinBox, "qt_calendar_yearedit"
        )

        self.year_spinbox.installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj is self.year_spinbox and event.type() == QtCore.QEvent.FocusIn:
            print(self.year_spinbox.value())

        return super().eventFilter(obj, event)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
like image 188
eyllanesc Avatar answered Dec 06 '25 07:12

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!