是否可以在QCalendarWidget中禁用星期六和星期日?

问题描述 投票:0回答:1

我希望用户能够在QCalendarWidget中选择星期一,星期二,星期三,星期四或星期五(工作日)。但不是周六或周日。 (周末)

  • 此功能是否适用于QCalendarWidget?
  • 如果没有,我如何禁用日历上的日期?
c++ qt qtwidgets qcalendarwidget
1个回答
0
投票

您可以编写自定义CalendarWidget并根据需要重新绘制单元格。根据您的要求,您可以查看date.dayOfWeek()是6还是7。

在此示例中,如果日期是工作日,则日历窗口小部件可以更改所选日期的颜色,如果日期是周末,则日历窗口小部件不会更改。但是,小部件日历仍然得到事件clicked。希望这有帮助。

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);
    }
}

编辑:

我添加了一个图像enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.