English Български

Customizing the appearance of QCalendarWidget

There are numerous ways to make a calendar. And the simplest one , must be using the QCalendarWidget [doc.qt.nokia.com]. However, we have limited control over the appearance of this widget.

Inheriting the QCalendarWidget [doc.qt.nokia.com] can solve the issue. Here is the example class which explains a ‘custom’ calendar widget.

The cells, or the particular days are customized, and in order to do this , we need to take control over the protected function paintCell [doc.qt.nokia.com]

Example:

  1. class ourCalendarWidget : public QCalendarWidget
  2. {
  3.  
  4. Q_OBJECT
  5.  
  6. public:
  7.          ourCalendarWidget(QWidget *parent = 0) : QCalendarWidget(parent){}
  8.         ~ourCalendarWidget() {}
  9.  
  10. void ourCall(QDate date)
  11. {
  12.     // here we set some conditions
  13.     update();
  14. }
  15.  
  16. protected:
  17. void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
  18. {
  19.     if ( ) // our conditions
  20.     {     // When the conditions are matched, passed QDate is drawn as we like.                              
  21.        
  22.         painter->save();
  23.         painter->drawEllipse(rect);   // here we draw n ellipse and the day--
  24.         painter->drawText(rec, Qt::TextSingleLine, Qt::AlignCenter,QString::number(date.day()));
  25.         painter->restore();
  26.     }
  27.     else
  28.     {   // if our conditions are not matching, show the default way.
  29.         QCalendarWidget::paintCell(painter, rect, date);
  30.     }
  31. }

That is all. Happy coding.

Categories: