📅  最后修改于: 2023-12-03 14:45:47.378000             🧑  作者: Mango
在 PyQt5 中,QCalendarWidget 组件是一个用于显示日历的 UI 组件。有时候我们需要在界面中显示上个月的日历,本文将介绍如何实现这个功能。
下面是完整的 Python 代码示例:
from PyQt5.QtWidgets import QApplication, QMainWindow, QCalendarWidget
from PyQt5.QtCore import QDate
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个 QCalendarWidget 组件
calendar_widget = QCalendarWidget(self)
self.setCentralWidget(calendar_widget)
# 获取当前日期并计算出上个月的月份和年份
current_date = QDate.currentDate()
current_year = current_date.year()
current_month = current_date.month()
last_month_year = current_year if current_month != 1 else current_year - 1
last_month_month = current_month - 1 if current_month != 1 else 12
# 创建一个上个月的 QDate 对象,并设置到 QCalendarWidget 中
last_month_date = QDate(last_month_year, last_month_month, 1)
calendar_widget.setSelectedDate(last_month_date)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
首先,在 MainWindow
类的构造函数中创建一个 QCalendarWidget 组件,并将其设为中心部件。
接下来,获取当前日期,计算出上个月的月份和年份。如果当前月份为 1,那么上个月的年份应该是当前年份减1。
创建一个上个月的 QDate 对象,通过 setSelectedDate
方法设置到 QCalendarWidget 中即可。
本文通过一个简单的例子演示了如何在 PyQt5 中实现显示上个月的 QCalendarWidget,希望对大家的学习有所帮助。