python - 在 Qt5 日历小部件中突出显示日期间隔

标签 python pyqt pyqt5 qcalendarwidget

我想在 CalendarWidget 中突出显示所选开始日期和结束日期之间的每一天。 我的问题是,CalendarWidget 只允许 QTCreator 中的 SingleSelection,但表示其他内容可以通过编程方式更改。

我发现了一些使用 QPainter 和 PaintCell() 方法的提示,但我不知道从哪里开始。互联网对我的情况没有帮助。 我尝试先在 ButtonClick 上更改单个日期,但即使这样也不起作用,您能给我建议如何使用它吗?

btn_test_pressed(self):
    painter = QPainter()
    painter.setPen(QtGui.QPen(QtCore.Qt.green))
    painter.fillRect(QtCore.QRectF(250, 250, 10, 10), 0, 5760)
    rect = QRect()
    date = datetime.datetime.now() - datetime.timedelta(1)
    self.calendarWidget.paintCell(painter, rect, date)

最佳答案

要更新单个日期的样式,您可以使用QCalendarWidget.setDateTextFormat()。以下是如何使用它来突出显示日期范围的基本实现,可以通过按住 Shift 键的同时选择开始日期和结束日期来选择日期范围。

from PyQt5.QtGui import QPalette, QTextCharFormat
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QCalendarWidget

class MyCalendar(QCalendarWidget):
    def __init__(self):
        super().__init__()
        self.begin_date = None
        self.end_date = None

        self.highlight_format = QTextCharFormat()
        self.highlight_format.setBackground(self.palette().brush(QPalette.Highlight))
        self.highlight_format.setForeground(self.palette().color(QPalette.HighlightedText))

        self.clicked.connect(self.date_is_clicked)
        print(super().dateTextFormat())

    def format_range(self, format):
        if self.begin_date and self.end_date:
            d0 = min(self.begin_date, self.end_date)
            d1 = max(self.begin_date, self.end_date)
            while d0 <= d1:
                self.setDateTextFormat(d0, format)
                d0 = d0.addDays(1)

    def date_is_clicked(self, date):
        # reset highlighting of previously selected date range
        self.format_range(QTextCharFormat())
        if QApplication.instance().keyboardModifiers() & Qt.ShiftModifier and self.begin_date:
            self.end_date = date
            # set highilighting of currently selected date range
            self.format_range(self.highlight_format)
        else:
            self.begin_date = date
            self.end_date = None

if __name__ == "__main__":
    app = QApplication([])
    calendar = MyCalendar()
    calendar.show()
    app.exec()

屏幕截图:

screenshot of calendar with selection

关于python - 在 Qt5 日历小部件中突出显示日期间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165586/

相关文章:

python - Pandas/Numpy 查找列标题和索引标题之间差异的方法

python - 如何用plotly绘制线的密度

python - 从对话框操作更改主窗口事件选项卡

python - 用户调整 PyQt 小部件的大小

python - 修改字体的大小和类型

python - 订阅者无法读取发布者的图像

python - NumPy 能否注意数组(非严格地)沿一个轴递增?

python - 如何编写一个用 python 调用自身的 bash 脚本?

python - PyQt5 固定窗口大小

python - 'QPixmap' 没有属性 'grabWindow'