Is it possible to disable Saturdays and Sundays in QCalendarWidget?

992 Views Asked by At

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?
1

There are 1 best solutions below

3
On

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