How to apply qss to a QCalendarWidget?

2.8k Views Asked by At

Good evening I am trying to generate a calendar like the one in the image:

enter image description here

So far what I have achieved with the QSS is this:

enter image description here

And this is the QSS that I have used

QCalendarWidget QAbstractItemView
{ 
selection-background-color: #042944; 
selection-color: white;
selection-border:10px solid red;

}
QCalendarWidget QWidget 
{
  color:grey;
}
QCalendarWidget QTableView{
border-width:0px;
background-color:lightgrey;
}

I still need to change the color of the days (Sunday and Saturday), and that when selecting a day the edge is round.

this is what I tried:

QCalendarWidget{
   color:grey;
}

QCalendarWidget QTableView::item:selected{
   border-radius:30px;

}

but it does not work I hope you can help me

1

There are 1 best solutions below

0
On BEST ANSWER

Not everything can be done with Qt Style Sheet, in fact it is very limited, in this case to change the color of the weekends you must use setWeekdayTextFormat() and to change the shape of the selected day you should use paintCell().

from PyQt5 import QtCore, QtGui, QtWidgets

QSS = '''
QCalendarWidget QAbstractItemView
{ 
    selection-background-color: #042944; 
    selection-color: white;
}
QCalendarWidget QWidget 
{
  color:grey;
}
QCalendarWidget QTableView
{
    border-width:0px;
    background-color:lightgrey;
}
'''

class CalendarWidget(QtWidgets.QCalendarWidget):
    def __init__(self, parent=None):
        super(CalendarWidget, self).__init__(parent,
            verticalHeaderFormat=QtWidgets.QCalendarWidget.NoVerticalHeader,
            gridVisible=False)

        for d in (QtCore.Qt.Saturday, QtCore.Qt.Sunday,):
            fmt = self.weekdayTextFormat(d)
            fmt.setForeground(QtCore.Qt.darkGray)
            self.setWeekdayTextFormat(d, fmt)

    def paintCell(self, painter, rect, date):
        if date == self.selectedDate():
            painter.save()
            painter.fillRect(rect, QtGui.QColor("#D3D3D3"))
            painter.setPen(QtCore.Qt.NoPen)
            painter.setBrush(QtGui.QColor("#33B5E5"))
            r = QtCore.QRect(QtCore.QPoint(), min(rect.width(), rect.height())*QtCore.QSize(1, 1))
            r.moveCenter(rect.center())
            painter.drawEllipse(r)
            painter.setPen(QtGui.QPen(QtGui.QColor("gray")))
            painter.drawText(rect, QtCore.Qt.AlignCenter, str(date.day()))
            painter.restore()
        else:
            super(CalendarWidget, self).paintCell(painter, rect, date)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet(QSS)
    w = CalendarWidget()
    w.show()
    sys.exit(app.exec_())

enter image description here