Qt provides lots of useful widgets for developer. The programmer just need to know how to use it in their own project. Today, I want to give a briefy demonstration for the use of the QCalendarWidget.
- Project: Qt Simple Calendar
- Skill Requirement:Basic C++ and Qt
- Difficulty: Beginner
Create a Qt gui project, and edit your ui file. Drag a Calendar widget from Qt Widget Box to your Qt Designer Editor. We also need three labels and three LineEdit.

then, click the "Edit Signals/Slots" to setup a slot.

Select the "clicked(QDate)" slots and click the right-hand side's "edit" button to setup a function name - "onDateSelected(QDate)" for the slots. Cause the slots will pass a QDate object to your slot handler, so don't forget the parameter type.

Edit your header file and add the slot into your header.
#ifndef SIMPLECALENDAR_H
#define SIMPLECALENDAR_H
#include <Qtgui/QWidget>
#include "ui_simplecalendar.h"
class SimpleCalendar : public QWidget
{
Q_OBJECT
public:
SimpleCalendar(QWidget *parent = 0);
~SimpleCalendar();
public slots:
void onDateSelected(QDate);
private:
Ui::SimpleCalendarClass ui;
};
#endif // SIMPLECALENDAR_H
Edit your class source code. When the clicked signal was emitted, this program will show the year, month and day on their own Line Edit.
#include "simplecalendar.h"
SimpleCalendar::SimpleCalendar(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
SimpleCalendar::~SimpleCalendar()
{
}
void SimpleCalendar::onDateSelected(QDate qdate){
QString str;
ui.yearLine->setText(str.number(qdate.year(),10));
ui.monthLine->setText(str.number(qdate.month(),10));
ui.dayLine->setText(str.number(qdate.day(),10));
}
Compile and Run:
Right-Click your Qt project to compile it. Your program could be similar to the screenshot.

Conclusion:
It's quite simple and efficient for creating a calendar in Qt. If you want to know more about the QCalendarWidget or other widgets. Please visit Qt Reference Documentation.
0 意見:
Post a Comment