본문 바로가기
놀기/Qt

[QT] QCalendarWidget의 paintCell()을 사용하여 선택한 날짜 색상 바꾸기

by Hi~ 2023. 4. 28.

QCalendarWidget의 paintCell()을 사용하여 선택한 날짜 색상 바꾸기

 

날짜를 선택하면 addDays() 함수를 호출해서 해당 날짜 색상을 바꿈.

 

 

#include <QDebug>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_calendarWidget = new QCalenderColorDateWidget(this);
    ui->mainVerticalLayout->addWidget(m_calendarWidget);

    QObject::connect(m_calendarWidget, SIGNAL(clicked(const QDate&)), this, SLOT(slotCalendarClicked(const QDate&)));
}


MainWindow::~MainWindow()
{
    if (nullptr != m_calendarWidget) {
        delete m_calendarWidget;
    }
    delete ui;
}


void MainWindow::slotCalendarClicked(const QDate& d)
{
    m_calendarWidget->addDays(d);
}

 

#include <QPainter>
#include <QDebug>

#include "qcalendercolordatewidget.h"

QCalenderColorDateWidget::QCalenderColorDateWidget(QWidget *parent): QCalendarWidget(parent)
{
}

void QCalenderColorDateWidget::addDays(const QDate &date)
{
    if (m_dates.contains(date)) {
        m_dates.removeAll(date);
    }
    else {
        m_dates << date;
    }

    updateCell(date);
}

void QCalenderColorDateWidget::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
{
    if (m_dates.contains(date)) {
        qDebug() << date;
        painter->save();
        painter->setBrush(Qt::red);
        painter->drawRect(rect);
        painter->drawText(rect, Qt::AlignCenter|Qt::TextSingleLine, QString::number(date.day()));
        painter->restore();
    }
    else {
        QCalendarWidget::paintCell(painter, rect, date);
    }
}

 

 

 

main.cpp
0.00MB
mainwindow.cpp
0.00MB
mainwindow.h
0.00MB
mainwindow.ui
0.00MB
qcalendercolordatewidget.cpp
0.00MB
qcalendercolordatewidget.h
0.00MB
runTEST_Calendar_ChangeColor.pro
0.00MB

 

댓글