Search code examples
qtqt4qtstylesheets

Qt QCalendarWidget QSS Styling


I know there's no support for QCalendarWidget QSS styling but does anyone know some workarounds for changing the color of sections 1 and 2 of the QCalendarWidget? (the light blue for section 1 and white for section 2)

enter image description here

Thanks!


Solution

  • 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.