Archived:How to create a Qt Calendar Widget
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (using C++ for the Qt app UI) is deprecated.
This article demonstrates how to create a Qt calendar widget (QCalendarWidget).
Article Metadata
Code Example
Tested with
Compatibility
Article
Contents |
Basic Idea
QCalendarWidget displays one calendar in month view and allows the user to select a date. The calendar widget has a navigation bar that allows the user to change the month, the dates are displayed in gird view and user can select one date. The top header represents the weekdays and the left header represents the week number in the year.
Class Definition
#ifndef CALENDARQT_H
#define CALENDARQT_H
#include <QWidget>
#include "QGroupBox"
#include "QCalendarWidget"
#include "QHBoxLayout"
namespace Ui {
class CalendarQt;
}
class QCalendarWidget;
class QGroupBox;
class QHBoxLayout;
class CalendarQt : public QWidget
{
Q_OBJECT
public:
explicit CalendarQt(QWidget *parent = 0);
~CalendarQt();
private:
Ui::CalendarQt *ui;
void CreateCalendarWidget();
QGroupBox *calendarGroupBox;
QCalendarWidget *calendar;
QHBoxLayout *calendarLayout;
};
#endif // CALENDARQT_H
Class Implementation
Lets start with the constructor .
CalendarQt::CalendarQt(QWidget *parent) :
QWidget(parent),
ui(new Ui::CalendarQt)
{
ui->setupUi(this);
CreateCalendarWidget();
QGridLayout *layout = new QGridLayout;
layout->addWidget(calendarGroupBox);
this-> setLayout(layout);
setWindowTitle(tr("Calendar"));
}
We create the calendar widget using the private function CreateCalendarWidget() and then arrange it to QGridLayout, and then set the QGridLayout to the main widget. setWindowTitle() is used to set the title of the main widget. Before we add the calendar widget to the QGridLayout in constructor, lets move on to the CreateCalendarWidget() function to understand how the calendar widget is being created.
void CalendarQt::CreateCalendarWidget()
{
calendarGroupBox = new QGroupBox(tr("Widget"));
calendar = new QCalendarWidget;
calendar->setMinimumDate(QDate(1947, 1, 1));
calendar->setMaximumDate(QDate(9999, 1, 1));
calendar->setGridVisible(true);
connect(calendar, SIGNAL(currentPageChanged(int,int)),
this, SLOT(reformatCalendarPage()));
calendarLayout = new QHBoxLayout;
calendarLayout->addWidget(calendar,Qt::AlignCenter);
calendarGroupBox->setLayout(calendarLayout);
}
TheQGroupBox contains only one widget i.e.QCalendarWidget. We set the QCalendarWidget to connect its currentPageChanged() signal to reformatCalendarPage() slot to make sure that every new page gets the formatting specified by the user. We create a QHBoxLayout , add the QCalendarWidget to the QHBoxLayout, and then set the QHBoxLayout to the QGroupBox. The max and min date are set with QCalendarWidget:: setMaximumDate() and QCalendarWidget:: setMinimumDate() functions.
Source Code
The full source code for this article is available here: File:CalendarQt.zip

