Search code examples
pythonpyqtpyqt5qcalendarwidget

How to add Today Button in QDateEdit Pop-up QCalendarWidget


Today Button like this

Image of my pop-up calendar widget:

Image of my pop-up calendar widget

I am trying to create simple Gui using PyQt5 in Python with date picker option. I need to add today button in QDateEdit in pop-up QCalendarWidget.


Solution

  • You must add the button to the QCalendarWidget through the layout, and when the button is pressed set the QDate::currentDate() as selectedDate of the QCalendarWidget:

    import sys
    
    from PyQt5 import QtCore, QtWidgets
    
    
    class DateEdit(QtWidgets.QDateEdit):
        def __init__(self, parent=None):
            super().__init__(parent, calendarPopup=True)
            self._today_button = QtWidgets.QPushButton(self.tr("Today"))
            self._today_button.clicked.connect(self._update_today)
            self.calendarWidget().layout().addWidget(self._today_button)
    
        @QtCore.pyqtSlot()
        def _update_today(self):
            self._today_button.clearFocus()
            today = QtCore.QDate.currentDate()
            self.calendarWidget().setSelectedDate(today)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = DateEdit()
        w.show()
        sys.exit(app.exec_())