0

我正在尝试覆盖 QCalendarWidget 的 paintCell() 方法以在今天的日期单元格上绘制红色轮廓并绘制将由用户定义的事件。对于我的日历,我使用 QItemDelegate 来更改日期标志的对齐方式,这样我就有更多空间来绘制事件。但是,我似乎无法让 QItemDelegate 和 paintCell() 一起工作。我一次只能完成一项或另一项工作。如果我尝试两者都做,则只有代表显示并且没有绘制任何内容。

from PySide2.QtWidgets import QMainWindow, QCalendarWidget, QApplication, QItemDelegate, QTableView
from PySide2.QtGui import QPen
from PySide2.QtCore import Qt
import sys


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.calendar = CustomCalendar()
        self.calendarview = self.calendar.findChild(QTableView, "qt_calendar_calendarview")
        self.calendardelegate = CalendarItemDelegate(self.calendarview)
        self.calendarview.setItemDelegate(self.calendardelegate)
        self.setCentralWidget(self.calendar)
        self.show()


class CustomCalendar(QCalendarWidget):
    def __init__(self, parent=None):
        super().__init__()

    def paintCell(self, painter, rect, date):
        QCalendarWidget.paintCell(self, painter, rect, date)
        pen = QPen()
        pen.setColor(Qt.red)
        painter.setPen(pen)
        if date == date.currentDate():
            painter.save()
            painter.drawRect(rect.adjusted(0, 0, -1, -1))
            painter.restore()


class CalendarItemDelegate(QItemDelegate):
    def paint(self, painter, option, index):
        painter._date_flag = index.row() > 0
        super().paint(painter, option, index)

    def drawDisplay(self, painter, option, rect, text):
        if painter._date_flag:
            option.displayAlignment = Qt.AlignTop | Qt.AlignLeft
        super().drawDisplay(painter, option, rect, text)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

我怎样才能让两者同时工作?

在此处输入图像描述

代表

在此处输入图像描述

油漆单元

4

1 回答 1

1

当在日历小部件上设置自定义项目委托时,默认值paintCell将被忽略,因为(私有)委托有责任调用它。

由于您使用的是 QItemDelegate,因此您可以利用该drawFocus()函数并检查是否设置option.stateState_Selected标志(从技术上讲,您也可以这样做drawDisplay(),因为无论如何都会调用该函数并且该选项具有相同的值):

    def drawFocus(self, painter, option, rect):
        super().drawFocus(painter, option, rect)
        if option.state & QStyle.State_Selected:
            painter.save()
            painter.setPen(Qt.red)
            painter.drawRect(rect.adjusted(0, 0, -1, -1))
            painter.restore()
于 2021-01-07T01:40:52.427 回答