In this lesson we want to learn about Python PySide6 QCalendarWidget, QCalendarWidget is user interface element that provides graphical representation of calendar. it enables the user to select date either by clicking on particular day or by scrolling through the months and years.
This is a simple example of how to use QCalendarWidget in PySide6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from PySide6.QtWidgets import QApplication, QMainWindow, QCalendarWidget import sys from PySide6.QtCore import QDate class Example(QMainWindow): def __init__(self): super().__init__() # create QCalendarWidget instance cal = QCalendarWidget(self) # set default date to today's date cal.setSelectedDate(QDate.currentDate()) # set th minimum and maximum date range cal.setMinimumDate(cal.selectedDate()) cal.setMaximumDate(cal.selectedDate().addMonths(1)) # set the window titl and central widget self.setWindowTitle('Calendar Widget') self.setCentralWidget(cal) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec()) |
In this example, we create a new QMainWindow and set its central widget to a QCalendarWidget instance. We also set the default date to today’s date, and set the minimum and maximum date range to one month.
Run the complete code and this will be the result.
Signals and Slots
QCalendarWidget emits signals when the user selects new date which can be used to update other parts of your application. you can connect these signals to custom functions using PySide6 signals and slots mechanism.
This is an example that demonstrates how to use signals and slots with QCalendarWidget:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout,QCalendarWidget, QLabel import sys class Example(QWidget): def __init__(self): super().__init__() self.setWindowTitle('Calendar Widget') vbox = QVBoxLayout() # create QCalendarWidget instanc cal = QCalendarWidget() # create QLabel to display selected date self.date_label = QLabel() self.date_label.setText(cal.selectedDate().toString()) # connect selectionChanged signal to updat the date label cal.selectionChanged.connect(self.update_date_label) vbox.addWidget(cal) vbox.addWidget(self.date_label) self.setLayout(vbox) def update_date_label(self): # update the date label with the new selected date selected_date = self.centralWidget().selectedDate().toString() self.date_label.setText(selected_date) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec()) |
In this example we have created new QMainWindow and QCalendarWidget instance, and QLabel to display the selected date. after that we connect the selectionChanged signal emitted by the calendar widget to a custom update_date_label() function, which updates the date label with the new selected date.
Run the complete code and this will be the result.