1

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

4

1 回答 1

2

一种可能的解决方案是通过显示日期的 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_())

在此处输入图像描述

于 2020-11-23T22:54:00.593 回答