Search code examples
pythonpyside2qcalendarwidget

Change Date Position To Top Left in QCalendarWidget


I am looking for a way to change the position of the date number in each cell of the QCalendarWidget (i.e., "1, 2, 3, 4... 31"). I would like it to be in the top left corner so I can have more room to paint events in date cells.

Image Explanation:
Image Explanation


Solution

  • A possible solution is to change the alignment of the text through a QTableView delegate that shows the dates:

    import sys
    
    from PySide2 import QtCore, QtWidgets
    
    
    class Delegate(QtWidgets.QItemDelegate):
        def paint(self, painter, option, index):
            # Dates are row and column cells greater than zero
            painter._date_flag = index.row() > 0 and index.column() > 0
            super().paint(painter, option, index)
    
        def drawDisplay(self, painter, option, rect, text):
            if painter._date_flag:
                option.displayAlignment = QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft
            super().drawDisplay(painter, option, rect, text)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
    
        calendar = QtWidgets.QCalendarWidget()
    
        qt_calendar_calendarview = calendar.findChild(
            QtWidgets.QTableView, "qt_calendar_calendarview"
        )
        qt_calendar_delegate = Delegate(qt_calendar_calendarview)
        qt_calendar_calendarview.setItemDelegate(qt_calendar_delegate)
    
        calendar.show()
    
        sys.exit(app.exec_())
    

    enter image description here