Calendar Widget Example▲
QCalendarWidget displays one calendar month at a time and lets the user select a date. The calendar consists of four components: a navigation bar that lets the user change the month that is displayed, a grid where each cell represents one day in the month, and two headers that display weekday names and week numbers.
The Calendar Widget example displays a QCalendarWidget and lets the user configure its appearance and behavior using QComboBoxes, QCheckBoxes, and QDateEdits. In addition, the user can influence the formatting of individual dates and headers.
The properties of the QCalendarWidget are summarized in the table below.
Property |
Description |
---|---|
The currently selected date. |
|
The earliest date that can be selected. |
|
The latest date that can be selected. |
|
The day that is displayed as the first day of the week (usually Sunday or Monday). |
|
Whether the grid should be shown. |
|
Whether the user can select a date or not. |
|
The format of the day names in the horizontal header (e.g., "M", "Mon", or "Monday"). |
|
The format of the vertical header. |
|
Whether the navigation bar at the top of the calendar widget is shown. |
The example consists of one class, Window, which creates and lays out the QCalendarWidget and the other widgets that let the user configure the QCalendarWidget.
Window Class Definition▲
Here is the definition of the Window class:
class
Window : public
QWidget
{
Q_OBJECT
public
:
Window(QWidget *
parent =
nullptr
);
private
slots:
void
localeChanged(int
index);
void
firstDayChanged(int
index);
void
selectionModeChanged(int
index);
void
horizontalHeaderChanged(int
index);
void
verticalHeaderChanged(int
index);
void
selectedDateChanged();
void
minimumDateChanged(QDate date);
void
maximumDateChanged(QDate date);
void
weekdayFormatChanged();
void
weekendFormatChanged();
void
reformatHeaders();
void
reformatCalendarPage();
private
:
void
createPreviewGroupBox();
void
createGeneralOptionsGroupBox();
void
createDatesGroupBox();
void
createTextFormatsGroupBox();
QComboBox *
createColorComboBox();
QGroupBox *
previewGroupBox;
QGridLayout *
previewLayout;
QCalendarWidget *
calendar;
QGroupBox *
generalOptionsGroupBox;
QLabel *
localeLabel;
QLabel *
firstDayLabel;
...
QCheckBox *
mayFirstCheckBox;
}
;
As is often the case with classes that represent self-contained windows, most of the API is private. We will review the private members as we stumble upon them in the implementation.
Window Class Implementation▲
Let's now review the class implementation, starting with the constructor:
Window::
Window(QWidget *
parent)
:
QWidget(parent)
{
createPreviewGroupBox();
createGeneralOptionsGroupBox();
createDatesGroupBox();
createTextFormatsGroupBox();
QGridLayout *
layout =
new
QGridLayout;
layout-&
gt;addWidget(previewGroupBox, 0
, 0
);
layout-&
gt;addWidget(generalOptionsGroupBox, 0
, 1
);
layout-&
gt;addWidget(datesGroupBox, 1
, 0
);
layout-&
gt;addWidget(textFormatsGroupBox, 1
, 1
);
layout-&
gt;setSizeConstraint(QLayout::
SetFixedSize);
setLayout(layout);
previewLayout-&
gt;setRowMinimumHeight(0
, calendar-&
gt;sizeHint().height());
previewLayout-&
gt;setColumnMinimumWidth(0
, calendar-&
gt;sizeHint().width());
setWindowTitle(tr("Calendar Widget"
));
}
We start by creating the four QGroupBoxes and their child widgets (including the QCalendarWidget) using four private create...GroupBox() functions, described below. Then we arrange the group boxes in a QGridLayout.
We set the grid layout's resize policy to QLayout::SetFixedSize to prevent the user from resizing the window. In that mode, the window's size is set automatically by QGridLayout based on the size hints of its contents widgets.
To ensure that the window isn't automatically resized every time we change a property of the QCalendarWidget (for example, hiding the navigation bar, the vertical header, or the grid), we set the minimum height of row 0 and the minimum width of column 0 to the initial size of the QCalendarWidget.
Let's move on to the createPreviewGroupBox() function:
void
Window::
createPreviewGroupBox()
{
previewGroupBox =
new
QGroupBox(tr("Preview"
));
calendar =
new
QCalendarWidget;
calendar-&
gt;setMinimumDate(QDate(1900
, 1
, 1
));
calendar-&
gt;setMaximumDate(QDate(3000
, 1
, 1
));
calendar-&
gt;setGridVisible(true
);
connect(calendar, &
amp;QCalendarWidget::
currentPageChanged,
this
, &
amp;Window::
reformatCalendarPage);
previewLayout =
new
QGridLayout;
previewLayout-&
gt;addWidget(calendar, 0
, 0
, Qt::
AlignCenter);
previewGroupBox-&
gt;setLayout(previewLayout);
}
The Preview group box contains only one widget: the QCalendarWidget. We set it up, connect its currentPageChanged() signal to our reformatCalendarPage() slot to make sure that every new page gets the formatting specified by the user.
The createGeneralOptionsGroupBox() function is somewhat large and several widgets are set up in the same way. We will look at parts of its implementation here and skip the rest:
void
Window::
createGeneralOptionsGroupBox()
{
generalOptionsGroupBox =
new
QGroupBox(tr("General Options"
));
localeCombo =
new
QComboBox;
int
curLocaleIndex =
-
1
;
int
index =
0
;
for
(int
_lang =
QLocale::
C; _lang &
lt;=
QLocale::
LastLanguage; ++
_lang) {
QLocale::
Language lang =
static_cast
&
lt;QLocale::
Language&
gt;(_lang);
const
auto
locales =
QLocale::
matchingLocales(lang, QLocale::
AnyScript, QLocale::
AnyTerritory);
for
(auto
loc : locales) {
QString label =
QLocale::
languageToString(lang);
auto
territory =
loc.territory();
label +=
QLatin1Char('/'
);
label +=
QLocale::
territoryToString(territory);
if
(locale().language() ==
lang &
amp;&
amp; locale().territory() ==
territory)
curLocaleIndex =
index;
localeCombo-&
gt;addItem(label, loc);
++
index;
}
}
if
(curLocaleIndex !=
-
1
)
localeCombo-&
gt;setCurrentIndex(curLocaleIndex);
localeLabel =
new
QLabel(tr("&Locale"
));
localeLabel-&
gt;setBuddy(localeCombo);
firstDayCombo =
new
QComboBox;
firstDayCombo-&
gt;addItem(tr("Sunday"
), Qt::
Sunday);
firstDayCombo-&
gt;addItem(tr("Monday"
), Qt::
Monday);
firstDayCombo-&
gt;addItem(tr("Tuesday"
), Qt::
Tuesday);
firstDayCombo-&
gt;addItem(tr("Wednesday"
), Qt::
Wednesday);
firstDayCombo-&
gt;addItem(tr("Thursday"
), Qt::
Thursday);
firstDayCombo-&
gt;addItem(tr("Friday"
), Qt::
Friday);
firstDayCombo-&
gt;addItem(tr("Saturday"
), Qt::
Saturday);
firstDayLabel =
new
QLabel(tr("Wee&k starts on:"
));
firstDayLabel-&
gt;setBuddy(firstDayCombo);
...
We start with the setup of the Week starts on combobox. This combobox controls which day should be displayed as the first day of the week.
The QComboBox class lets us attach user data as a QVariant to each item. The data can later be retrieved with QComboBox's itemData() function. QVariant doesn't directly support the Qt::DayOfWeek data type, but it supports int, and C++ will happily convert any enum value to int.
...
connect(localeCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
localeChanged);
connect(firstDayCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
firstDayChanged);
connect(selectionModeCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
selectionModeChanged);
connect(gridCheckBox, &
amp;QCheckBox::
toggled,
calendar, &
amp;QCalendarWidget::
setGridVisible);
connect(navigationCheckBox, &
amp;QCheckBox::
toggled,
calendar, &
amp;QCalendarWidget::
setNavigationBarVisible);
connect(horizontalHeaderCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
horizontalHeaderChanged);
connect(verticalHeaderCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
verticalHeaderChanged);
...
After having created the widgets, we connect the signals and slots. We connect the comboboxes to private slots of Window or to public slots provided by QComboBox.
...
firstDayChanged(firstDayCombo-&
gt;currentIndex());
selectionModeChanged(selectionModeCombo-&
gt;currentIndex());
horizontalHeaderChanged(horizontalHeaderCombo-&
gt;currentIndex());
verticalHeaderChanged(verticalHeaderCombo-&
gt;currentIndex());
}
At the end of the function, we call the slots that update the calendar to ensure that the QCalendarWidget is synchronized with the other widgets on startup.
Let's now take a look at the createDatesGroupBox() private function:
void
Window::
createDatesGroupBox()
{
datesGroupBox =
new
QGroupBox(tr("Dates"
));
minimumDateEdit =
new
QDateEdit;
minimumDateEdit-&
gt;setDisplayFormat("MMM d yyyy"
);
minimumDateEdit-&
gt;setDateRange(calendar-&
gt;minimumDate(),
calendar-&
gt;maximumDate());
minimumDateEdit-&
gt;setDate(calendar-&
gt;minimumDate());
minimumDateLabel =
new
QLabel(tr("&Minimum Date:"
));
minimumDateLabel-&
gt;setBuddy(minimumDateEdit);
currentDateEdit =
new
QDateEdit;
currentDateEdit-&
gt;setDisplayFormat("MMM d yyyy"
);
currentDateEdit-&
gt;setDate(calendar-&
gt;selectedDate());
currentDateEdit-&
gt;setDateRange(calendar-&
gt;minimumDate(),
calendar-&
gt;maximumDate());
currentDateLabel =
new
QLabel(tr("&Current Date:"
));
currentDateLabel-&
gt;setBuddy(currentDateEdit);
maximumDateEdit =
new
QDateEdit;
maximumDateEdit-&
gt;setDisplayFormat("MMM d yyyy"
);
maximumDateEdit-&
gt;setDateRange(calendar-&
gt;minimumDate(),
calendar-&
gt;maximumDate());
maximumDateEdit-&
gt;setDate(calendar-&
gt;maximumDate());
maximumDateLabel =
new
QLabel(tr("Ma&ximum Date:"
));
maximumDateLabel-&
gt;setBuddy(maximumDateEdit);
In this function, we create the Minimum Date, Maximum Date, and Current Date editor widgets, which control the calendar's minimum, maximum, and selected dates. The calendar's minimum and maximum dates have already been set in createPrivewGroupBox(); we can then set the widgets default values to the calendars values.
connect(currentDateEdit, &
amp;QDateEdit::
dateChanged,
calendar, &
amp;QCalendarWidget::
setSelectedDate);
connect(calendar, &
amp;QCalendarWidget::
selectionChanged,
this
, &
amp;Window::
selectedDateChanged);
connect(minimumDateEdit, &
amp;QDateEdit::
dateChanged,
this
, &
amp;Window::
minimumDateChanged);
connect(maximumDateEdit, &
amp;QDateEdit::
dateChanged,
this
, &
amp;Window::
maximumDateChanged);
...
}
We connect the currentDateEdit's dateChanged() signal directly to the calendar's setSelectedDate() slot. When the calendar's selected date changes, either as a result of a user action or programmatically, our selectedDateChanged() slot updates the Current Date editor. We also need to react when the user changes the Minimum Date and Maximum Date editors.
Here is the createTextFormatsGroup() function:
void
Window::
createTextFormatsGroupBox()
{
textFormatsGroupBox =
new
QGroupBox(tr("Text Formats"
));
weekdayColorCombo =
createColorComboBox();
weekdayColorCombo-&
gt;setCurrentIndex(
weekdayColorCombo-&
gt;findText(tr("Black"
)));
weekdayColorLabel =
new
QLabel(tr("&Weekday color:"
));
weekdayColorLabel-&
gt;setBuddy(weekdayColorCombo);
weekendColorCombo =
createColorComboBox();
weekendColorCombo-&
gt;setCurrentIndex(
weekendColorCombo-&
gt;findText(tr("Red"
)));
weekendColorLabel =
new
QLabel(tr("Week&end color:"
));
weekendColorLabel-&
gt;setBuddy(weekendColorCombo);
We set up the Weekday Color and Weekend Color comboboxes using createColorCombo(), which instantiates a QComboBox and populates it with colors ("Red", "Blue", etc.).
headerTextFormatCombo =
new
QComboBox;
headerTextFormatCombo-&
gt;addItem(tr("Bold"
));
headerTextFormatCombo-&
gt;addItem(tr("Italic"
));
headerTextFormatCombo-&
gt;addItem(tr("Plain"
));
headerTextFormatLabel =
new
QLabel(tr("&Header text:"
));
headerTextFormatLabel-&
gt;setBuddy(headerTextFormatCombo);
firstFridayCheckBox =
new
QCheckBox(tr("&First Friday in blue"
));
mayFirstCheckBox =
new
QCheckBox(tr("May &1 in red"
));
The Header Text Format combobox lets the user change the text format (bold, italic, or plain) used for horizontal and vertical headers. The First Friday in blue and May 1 in red check box affect the rendering of specific dates.
connect(weekdayColorCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
weekdayFormatChanged);
connect(weekdayColorCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
reformatCalendarPage);
connect(weekendColorCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
weekendFormatChanged);
connect(weekendColorCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
reformatCalendarPage);
connect(headerTextFormatCombo, &
amp;QComboBox::
currentIndexChanged,
this
, &
amp;Window::
reformatHeaders);
connect(firstFridayCheckBox, &
amp;QCheckBox::
toggled,
this
, &
amp;Window::
reformatCalendarPage);
connect(mayFirstCheckBox, &
amp;QCheckBox::
toggled,
this
, &
amp;Window::
reformatCalendarPage);
We connect the check boxes and comboboxes to various private slots. The First Friday in blue and May 1 in red check boxes are both connected to reformatCalendarPage(), which is also called when the calendar switches month.
...
reformatHeaders();
reformatCalendarPage();
}
At the end of createTextFormatsGroupBox(), we call private slots to synchronize the QCalendarWidget with the other widgets.
We're now done reviewing the four create...GroupBox() functions. Let's now take a look at the other private functions and slots.
QComboBox *
Window::
createColorComboBox()
{
QComboBox *
comboBox =
new
QComboBox;
comboBox-&
gt;addItem(tr("Red"
), QColor(Qt::
red));
comboBox-&
gt;addItem(tr("Blue"
), QColor(Qt::
blue));
comboBox-&
gt;addItem(tr("Black"
), QColor(Qt::
black));
comboBox-&
gt;addItem(tr("Magenta"
), QColor(Qt::
magenta));
return
comboBox;
}
In createColorCombo(), we create a combobox and populate it with standard colors. The second argument to QComboBox::addItem() is a QVariant storing user data (in this case, QColor objects).
This function was used to set up the Weekday Color and Weekend Color comboboxes.
void
Window::
firstDayChanged(int
index)
{
calendar-&
gt;setFirstDayOfWeek(Qt::
DayOfWeek(
firstDayCombo-&
gt;itemData(index).toInt()));
}
When the user changes the Week starts on combobox's value, firstDayChanged() is invoked with the index of the combobox's new value. We retrieve the custom data item associated with the new current item using itemData() and cast it to a Qt::DayOfWeek.
selectionModeChanged(), horizontalHeaderChanged(), and verticalHeaderChanged() are very similar to firstDayChanged(), so they are omitted.
void
Window::
selectedDateChanged()
{
currentDateEdit-&
gt;setDate(calendar-&
gt;selectedDate());
}
The selectedDateChanged() updates the Current Date editor to reflect the current state of the QCalendarWidget.
void
Window::
minimumDateChanged(QDate date)
{
calendar-&
gt;setMinimumDate(date);
maximumDateEdit-&
gt;setDate(calendar-&
gt;maximumDate());
}
When the user changes the minimum date, we tell the QCalenderWidget. We also update the Maximum Date editor, because if the new minimum date is later than the current maximum date, QCalendarWidget will automatically adapt its maximum date to avoid a contradicting state.
void
Window::
maximumDateChanged(QDate date)
{
calendar-&
gt;setMaximumDate(date);
minimumDateEdit-&
gt;setDate(calendar-&
gt;minimumDate());
}
maximumDateChanged() is implemented similarly to minimumDateChanged().
void
Window::
weekdayFormatChanged()
{
QTextCharFormat format;
format.setForeground(qvariant_cast&
lt;QColor&
gt;(
weekdayColorCombo-&
gt;itemData(weekdayColorCombo-&
gt;currentIndex())));
calendar-&
gt;setWeekdayTextFormat(Qt::
Monday, format);
calendar-&
gt;setWeekdayTextFormat(Qt::
Tuesday, format);
calendar-&
gt;setWeekdayTextFormat(Qt::
Wednesday, format);
calendar-&
gt;setWeekdayTextFormat(Qt::
Thursday, format);
calendar-&
gt;setWeekdayTextFormat(Qt::
Friday, format);
}
Each combobox item has a QColor object as user data corresponding to the item's text. After fetching the colors from the comboboxes, we set the text format of each day of the week.
The text format of a column in the calendar is given as a QTextCharFormat, which besides the foreground color lets us specify various character formatting information. In this example, we only show a subset of the possibilities.
void
Window::
weekendFormatChanged()
{
QTextCharFormat format;
format.setForeground(qvariant_cast&
lt;QColor&
gt;(
weekendColorCombo-&
gt;itemData(weekendColorCombo-&
gt;currentIndex())));
calendar-&
gt;setWeekdayTextFormat(Qt::
Saturday, format);
calendar-&
gt;setWeekdayTextFormat(Qt::
Sunday, format);
}
weekendFormatChanged() is the same as weekdayFormatChanged(), except that it affects Saturday and Sunday instead of Monday to Friday.
void
Window::
reformatHeaders()
{
QString text =
headerTextFormatCombo-&
gt;currentText();
QTextCharFormat format;
if
(text ==
tr("Bold"
))
format.setFontWeight(QFont::
Bold);
else
if
(text ==
tr("Italic"
))
format.setFontItalic(true
);
else
if
(text ==
tr("Green"
))
format.setForeground(Qt::
green);
calendar-&
gt;setHeaderTextFormat(format);
}
The reformatHeaders() slot is called when the user changes the text format of the headers. We compare the current text of the Header Text Format combobox to determine which format to apply. (An alternative would have been to store QTextCharFormat values alongside the combobox items.)
void
Window::
reformatCalendarPage()
{
QTextCharFormat mayFirstFormat;
const
QDate mayFirst(calendar-&
gt;yearShown(), 5
, 1
);
QTextCharFormat firstFridayFormat;
QDate firstFriday(calendar-&
gt;yearShown(), calendar-&
gt;monthShown(), 1
);
while
(firstFriday.dayOfWeek() !=
Qt::
Friday)
firstFriday =
firstFriday.addDays(1
);
if
(firstFridayCheckBox-&
gt;isChecked()) {
firstFridayFormat.setForeground(Qt::
blue);
}
else
{
// Revert to regular colour for this day of the week.
Qt::
DayOfWeek dayOfWeek(static_cast
&
lt;Qt::
DayOfWeek&
gt;(firstFriday.dayOfWeek()));
firstFridayFormat.setForeground(calendar-&
gt;weekdayTextFormat(dayOfWeek).foreground());
}
calendar-&
gt;setDateTextFormat(firstFriday, firstFridayFormat);
// When it is checked, "May First in Red" always takes precedence over "First Friday in Blue".
if
(mayFirstCheckBox-&
gt;isChecked()) {
mayFirstFormat.setForeground(Qt::
red);
}
else
if
(!
firstFridayCheckBox-&
gt;isChecked() ||
firstFriday !=
mayFirst) {
// We can now be certain we won't be resetting "May First in Red" when we restore
// may 1st's regular colour for this day of the week.
Qt::
DayOfWeek dayOfWeek(static_cast
&
lt;Qt::
DayOfWeek&
gt;(mayFirst.dayOfWeek()));
calendar-&
gt;setDateTextFormat(mayFirst, calendar-&
gt;weekdayTextFormat(dayOfWeek));
}
calendar-&
gt;setDateTextFormat(mayFirst, mayFirstFormat);
}
In reformatCalendarPage(), we set the text format of the first Friday in the month and May 1 in the current year. The text formats that are actually used depend on which check boxes are checked and what the weekday/weekend formats are.
QCalendarWidget lets us set the text format of individual dates with the setDateTextFormat(). We chose to set the date formats when the calendar page changes - i.e. a new month is displayed - and when the weekday/weekend format is changed. We check which of the mayFirstCheckBox and firstDayCheckBox, if any, are checked and set the text formats accordingly.