在 QCalendarWidget 中将日期位置更改为左上角

Change Date Position To Top Left in QCalendarWidget

我正在寻找一种方法来更改日期编号在 QCalendarWidget 的每个单元格中的位置(即“1、2、3、4...31”)。我希望它位于左上角,这样我就有更多空间在日期单元格中绘制事件。

图片说明:

一个可能的解决方案是通过显示日期的 QTableView 委托更改文本的对齐方式:

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_())