0

我想创建日历,它将标记用户输入的几个日期。所以我继承了 QCalendarWidget 并重新实现了 painCell 函数。这是我的简化代码:

MyCalendar::MyCalendar(QWidget *parent)
    : QCalendarWidget(parent)
{   
    painter = new QPainter(this);   
}
void MyCalendar::setHolidays(QDate date)
{
    paintCell(painter, rect(),date);        
}

void MyCalendar::paintCell(QPainter * painter, const QRect & rect, const QDate & date) const
{
    painter->setBrush(Qt::red);
    QCalendarWidget::paintCell(painter, rect, date);
}

但是我不能这样做,因为在创建 QPainter 对象时我收到以下消息:“QWidget::paintEngine: 不应再称为 QPainter::begin: Paint device returned engine == 0, type: 1”

当我没有设置画家父级时,我在尝试设置画笔时收到此错误:“QPainter::setBrush: Painter not active” 我想,我在错误的地方创建 QPainter 对象。任何人都知道,如何解决这个问题?

我正在使用 Qt wiki 片段: https ://wiki.qt.io/How_to_create_a_custom_calender_widget

4

1 回答 1

2

由于paintCell方法是内部调用的,所以不应该直接绘制,将日期保存在列表中是合适的,如果paintCell使用的日期包含在该列表中,请以个性化的方式进行绘制:

#ifndef MYCALENDAR_H
#define MYCALENDAR_H

#include <QCalendarWidget>
#include <QPainter>
class MyCalendar : public QCalendarWidget
{
public:
    MyCalendar(QWidget *parent=Q_NULLPTR):QCalendarWidget{parent}{

    }
    void addHoliday(const QDate &date){
        mDates<<date;
        updateCell(date);
    }
    void paintCell(QPainter * painter, const QRect & rect, const QDate & date) const{
        if(mDates.contains(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);

    }
private:
    QList<QDate> mDates;
};

#endif // MYCALENDAR_H
于 2018-01-15T12:33:41.980 回答