我的目标是禁用用户可以单击 a 中非当前月份的日期QCalendarWidget
,因此我将小部件子类化以执行此操作。到目前为止,我可以让那些日子根本不呈现任何文本(很棒)。这是代码:
class QCustomCalendar(QCalendarWidget):
"""Create my own Calendar with my own options."""
def __init__(self, parent=None):
"""Initializing functions"""
QCalendarWidget.__init__(self, parent)
self.setEnabled(True)
self.setGeometry(QRect(0, 0, 320, 250))
self.setGridVisible(False)
self.setHorizontalHeaderFormat(QCalendarWidget.SingleLetterDayNames)
self.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
self.setNavigationBarVisible(True)
self.setDateEditEnabled(True)
self.setObjectName("calendarWidget")
def paintCell(self, painter, rect, date):
"""Sub-class this and repaint the cells"""
# Render only this-month days
month = "{0}-{1}".format(str(self.yearShown()), str(self.monthShown()).zfill(2))
day = str(date.toPython())
if not day.startswith(month):
return
QCalendarWidget.paintCell(self, painter, rect, date)
但是,如果我单击未渲染的日期,它仍然会计数并触发clicked
事件。示例:我对一个红色方块进行了 photoshop,点击它,它会选择 6 月 4 日(即使我们在屏幕截图中是 5 月)。
我如何禁用那些日子而不是可选择的?
我尝试setDateRange
了currentPageChanged
事件,但它没有按预期工作:
def __init__(self, parent=None):
# some code
self.currentPageChanged.connect(self.store_current_month)
self.clicked.connect(self.calendar_itemchosen)
def store_current_month(self):
self.CURRENT_MONTH = "{0}-{1}".format(str(self.yearShown()), str(self.monthShown()).zfill(2))
def calendar_itemchosen(self):
day = str(self.selectedDate().toPython())
print(day)
if day.startswith(self.CURRENT_MONTH):
selection = self.selectedDate()
# some code
self.close()
使用此代码单击该红色方块的结果是:
2018-06
2018-06-04
currentPageChanged
所以我猜当您选择另一个月份的日期时,Qt 会首先触发该事件。setDateRange
将不起作用,因为如果我将其添加为仅限本月的选择,那么日历顶部的“转到下个月或上个月”的按钮将不起作用,我需要用户能够更改月份. 我只是不希望日历显示不属于本月页面的日期。