PyQt5 - QCalendar Widget



QCalendar widget is a useful date picker control. It provides a month-based view. The user can select the date by the use of the mouse or the keyboard, the default being today’s date. Calendar’s date range can also be stipulated.

Following are some utility methods of this class −

Sr.No. Methods & Description
1

setDateRange()

Sets the lower and upper date available for selection

2

setFirstDayOfWeek()

Determines the day of the first column in the calendar

The predefined day constants are −

  • Qt.Monday
  • Qt.Tuesday
  • Qt.Wednesday
  • Qt.Thursday
  • Qt.Friday
  • Qt.Saturday
  • Qt.Sunday
3

setMinimumDate()

Sets the lower date for selection

4

setMaximumDate()

Sets the upper date for selection

5

setSelectedDate()

Sets a QDate object as the selected date

6

showToday()

Shows the month of today

7

selectedDate()

Retrieves the selected date

8

setGridvisible()

Turns the calendar grid on or off

Example

The following example has a calendar widget and a label which displays the currently selected date. The complete code is as follows −

import sys
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QtGui.QWidget):
   def __init__(self):
      super(Example, self).__init__()
      self.initUI()
		
   def initUI(self):
      cal = QtGui.QCalendarWidget(self)
      cal.setGridVisible(True)
      cal.move(20, 20)
      cal.clicked[QtCore.QDate].connect(self.showDate)
		
      self.lbl = QtGui.QLabel(self)
      date = cal.selectedDate()
      self.lbl.setText(date.toString())
      self.lbl.move(20, 200)
		
      self.setGeometry(100,100,300,300)
      self.setWindowTitle('Calendar')
      self.show()
		
   def showDate(self, date):
	
      self.lbl.setText(date.toString())
		
def main():

   app = QtGui.QApplication(sys.argv)
   ex = Example()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()

The above code produces the following output. Selected date is displayed on the label −

QCalendar Widget Output
pyqt_basic_widgets.htm
Advertisements