In this lesson we are going to learn How to Create Calendar in Python & PyQt6, for creating of calendar in python & pyqt6 we are going to use QCalendarWidget class, so the QCalendarWidget class provides a monthly based calendar widget allowing the user to select a date , The widget is initialized with the current month and year, but QCalendarWidget provides several public slots or methods to change the year and month that is shown.
- How to Use Qt Designer in PyQt and PyQt6
- Build Text to Speech App with Python & PyQt5
- How to Build GUI Window in PyQt6
- How to Show Image in PyQt6
There are different methods that you can use.
- selectedDate(): This method returns the currently selected date. The date is
returned as a QDate object. - monthShown(): This method returns the currently displayed month.
- yearShown(): This method returns the currently displayed year.
- setFirstDayOfWeek(): This method is used to set the day of the week in the
first column. - selectionChanged(): This method is emitted when the user changes the
currently selected date.
This is the complete code for this article
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 38 39 40 41 |
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QCalendarWidget ,QVBoxLayout from PyQt6.QtGui import QIcon, QFont import sys class Window(QWidget): def __init__(self): super().__init__() self.setGeometry(200, 200, 700, 400) self.setWindowTitle("PyQt6 QCalendarWidget") self.setWindowIcon(QIcon('python.png')) vbox = QVBoxLayout() self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) self.calendar.selectionChanged.connect(self.calendar_date) self.label = QLabel("Hello") self.label.setFont(QFont("Sanserif", 15)) self.label.setStyleSheet('color:green') vbox.addWidget(self.calendar) vbox.addWidget(self.label) self.setLayout(vbox) def calendar_date(self): dateselected = self.calendar.selectedDate() date_in_string = str(dateselected.toPyDate()) self.label.setText("Date Is : " + date_in_string) app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec()) |
In here we have crate vertical box layout using QVBoxLayout.
1 |
vbox = QVBoxLayout() |
We have created the object of QCalendarWidget, also we have added the grid for the
calendar.
1 2 |
self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) |
In here we have connected the selectionChanged signal of QCalendarWidget with the method that we are going to create.
1 |
self.calendar.selectionChanged.connect(self.calendar_date) |
In this method we have received the selected date from the calendar and after that we have set that in the label.
1 2 3 4 5 |
def calendar_date(self): dateselected = self.calendar.selectedDate() date_in_string = str(dateselected.toPyDate()) self.label.setText("Date Is : " + date_in_string) |
Run the complete code and this will be the result.