1

I want the user to be able to select Monday, Tuesday, Wednesday, Thursday or Friday (weekdays) in a QCalendarWidget. But not Saturday or Sunday. (weekend)

  • Is this feature available for QCalendarWidget?
  • If not, how do I disable a date on the calendar?
ukll
  • 204
  • 2
  • 12
  • It seems that the solution is not finalized, so I think that answer is invalid, so I will remove my closing vote. – eyllanesc Dec 28 '17 at 05:11

1 Answers1

0

You can write a custom CalendarWidget and re-paint the cell as you want. As your request, you can check date.dayOfWeek() is 6 or 7.

In this example, calendar widget can change color of selected date if the date is weekdays and no change if the date is weekends. But, the widget calendar still get event clicked. Hope this help.

TestCalendar.h

class TestCalendar: public QCalendarWidget//: public QWidget//
{
    Q_OBJECT

    Q_PROPERTY(QColor color READ getColor WRITE setColor)
public:
    TestCalendar(QWidget* parent = 0);//();//
    ~TestCalendar();

    void setColor(QColor& color);
    QColor getColor();

protected:
    virtual void paintCell(QPainter* painter, const QRect &rect, const QDate &date) const;

private:

    QDate m_currentDate;
    QPen m_outlinePen;
    QBrush m_transparentBrush;
};

TestCalendar.cpp

#include <QtWidgets>

#include "TestCalendar.h"

TestCalendar::TestCalendar(QWidget *parent)
    : QCalendarWidget(parent)
{   
    m_currentDate = QDate::currentDate();
    m_outlinePen.setColor(Qt::blue);
    m_transparentBrush.setColor(Qt::transparent);
}

TestCalendar::~TestCalendar()
{
}

void TestCalendar::setColor(QColor &color)
{
    m_outlinePen.setColor(color);
}

QColor TestCalendar::getColor()
{
    return m_outlinePen.color();
}

void TestCalendar::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
{   
    if (date.dayOfWeek() == 6 or date.dayOfWeek() == 7) {
        painter->save();
        painter->drawText(rect, Qt::AlignCenter,QString::number(date.day()));
        painter->restore();
    } else {
        QCalendarWidget::paintCell(painter, rect, date);
    }
}

EDIT:

I add an image enter image description here

GAVD
  • 1,977
  • 3
  • 22
  • 40
  • Thank you for the answer. Your code compiles. However, it doesn't change the color of any day neither weekdays nor weekend. Also, in the header file there is a QCalendarWidget pointer declaration. But it is not used in anywhere. Did you forget anything? – ukll Dec 29 '17 at 08:36
  • Sorry, I forgot test code `*calendar`. When you click on weekdays, is it change color? – GAVD Dec 29 '17 at 08:41
  • Your code changes the color of numbers in weekends to black and background to white. But it does nothing else. It even does not change the numbers to other colors. Sorry for the frequent edits. – ukll Dec 29 '17 at 09:00