如何将QSS应用于QCalendarWidget?

时间:2018-12-12 00:50:10

标签: python pyqt pyqt5 qtstylesheets qcalendarwidget

晚上好,我正在尝试生成与图片中的日历类似的日历:

enter image description here

到目前为止,我在QSS上所取得的成就是:

enter image description here

这是我使用的QSS

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;
}

我仍然需要更改日期的颜色(星期日和星期六),并且在选择日期时边缘是圆形的。

这是我尝试过的:

QCalendarWidget{
   color:grey;
}

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

}

但是它不起作用,希望您能帮助我

1 个答案:

答案 0 :(得分:1)

Qt样式表无法完成所有操作,实际上它非常有限,在这种情况下,您必须使用setWeekdayTextFormat()来更改周末的颜色并更改您应该使用的所选日期的形状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