PyQt QCalendarWidget
You can use QCalendarWidget to display a calendar so that users can select a date.
The calendar is displayed on a monthly basis and is selected as the current year, month, and date when it first runs.
Related course: Create Desktop Apps with Python PyQt5
QCalenderWidget
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QCalendarWidget
from PyQt5.QtCore import QDate
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
cal = QCalendarWidget(self)
cal.setGridVisible(True)
cal.clicked[QDate].connect(self.showDate)
self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())
vbox = QVBoxLayout()
vbox.addWidget(cal)
vbox.addWidget(self.lbl)
self.setLayout(vbox)
self.setWindowTitle('QCalendarWidget')
self.setGeometry(300, 300, 400, 300)
self.show()
def showDate(self, date):
self.lbl.setText(date.toString())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
One calendar and one label that displays the date appear in the widget window.
Description
cal = QCalendarWidget(self)
cal.setGridVisible(True)
cal.clicked[QDate].connect(self.showDate)
Create one object (cal) for QCalenderWidget.
If set ToGridVisible (True), a grid is displayed between dates.
Connects the showDate method to be called when the date is clicked.
self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())
SelectedDate has the currently selected date information. (The default is the current date)
Displays the current date information on the label.
vbox = QVBoxLayout()
vbox.addWidget(cal)
vbox.addWidget(self.lbl)
Using a vertical box layout, you can place calendars and labels vertically.
def showDate(self, date):
self.lbl.setText(date.toString())
In the showDate method, each time you click a date, the label text is displayed as the selected date (date.toString()).
Related course: Create Desktop Apps with Python PyQt5