Qt QCalendarWidget QSS Styling

让人想犯罪 __ 提交于 2019-12-04 16:09:39

I've examined QCalendarWidget source code and found the solution.

QCalendarWidget internally has a model and a view to display days. QCalendarModel has a formatForCell(int, int) function that returns QTextCharFormat for a given cell. Returning format is the result of merging QCalendarView palette data, a format for current day (saturday and sunday are shown in red) and a format for current date, which can be set using QCalendarWidget::setDateTextFormat function.

Actually an item's background is:

format.setBackground(pal.brush(cg, header ? QPalette::AlternateBase : QPalette::Base));
  • pal is a QCalendarView's palette;
  • cg is a color group;
  • header is true when the current cell is a header cell (section 1 in your example)

So, all you need is to set your custom palette to that internal QCalendarView. In the source code we can find that QCalendarView object has a name "qt_calendar_calendarview" which we can use:

QCalendarWidget *c = new QCalendarWidget;

QTableView *view = c->findChild<QTableView*>("qt_calendar_calendarview");
if (view)
{
    QPalette pal = view->palette();
    pal.setColor(QPalette::Base, Qt::red);
    pal.setColor(QPalette::AlternateBase, Qt::green);
    view->setPalette(pal);
}

In my example section 1 will be red and section 2 will be green. Additionally you can set colors for every color group of you palette to get the widget you like when it's active, inactive etc.

Area "1" customization:

QTextCharFormat format;
format.setForeground(QBrush(Qt::blue));
format.setBackground(QBrush(Qt::red);
ui->calendarWidget->setHeaderTextFormat(format);

Area "2" QSS CSS:

QCalendarWidget QAbstractItemView
{
background-color: rgb(192,192,192); /* цвет фона текущего месяца */
selection-background-color: yellow; /* цвет фона выбранного дня */
selection-color: black; /* цвет текста выбранного дня */
}

or

#qt_calendar_calendarview
{
background-color: rgb(192,192,192); /* цвет фона текущего месяца */
selection-background-color: yellow; /* цвет фона выбранного дня */
selection-color: black; /* цвет текста выбранного дня */
}

, where #qt_calendar_calendarview - object's name from d->m_view->setObjectName(QLatin1String("qt_calendar_calendarview")); in qcalendarwidget.cpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!