You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QDateEdit适配波斯历(Jalali)有效日期被强制修改问题求助

问题原因

QDate是基于**公历(格里高利历)**实现的,你直接传入波斯历的1403/06/31,QDate会把它当成公历日期验证——但公历6月最多只有30天,这个日期会被判定为无效,QDate就返回默认的无效日期(2000/01/01),最终导致QDateEdit显示异常。

解决方案

要在QDateEdit里正确用波斯历,核心是把波斯历日期转成公历后再传给QDateEdit,同时保持显示格式为波斯历样式;如果要让下拉日历也显示波斯历,就得自定义日历模型。

方案1:基础适配(仅显示波斯历)

用persiantools的JalaliDate.to_gregorian()把波斯历转成公历QDate,同时设置QDateEdit的显示格式和波斯语区域,保证显示的是波斯历的年月日:

from persiantools.jdatetime import JalaliDate
import sys
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QDateEdit)
from PySide6.QtCore import QDate, Qt, QLocale

class Program(QWidget):
    def __init__(self):
        super().__init__()

        self.layout = QVBoxLayout()

        self.date_input = QDateEdit(self)
        # 设置显示格式为波斯历的年/月/日
        self.date_input.setDisplayFormat("yyyy/MM/dd")
        # 把最小波斯历日期转成公历再设置
        min_jalali = JalaliDate(1300, 1, 1)
        self.date_input.setMinimumDate(QDate(min_jalali.to_gregorian().year, 
                                             min_jalali.to_gregorian().month, 
                                             min_jalali.to_gregorian().day))
        
        # 生成目标波斯历日期,转成公历后设置
        jalali_date = JalaliDate(1403, 6, 31)
        gregorian_date = QDate(jalali_date.to_gregorian().year, 
                               jalali_date.to_gregorian().month, 
                               jalali_date.to_gregorian().day)
        self.date_input.setDate(gregorian_date)
        
        # 设置波斯语区域,确保显示波斯数字和格式
        locale = QLocale(QLocale.Persian, QLocale.Iran)
        self.date_input.setLocale(locale)
        
        self.date_input.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.date_input.setFixedWidth(150)

        input_layout = QHBoxLayout()
        input_layout.addWidget(self.date_input)
        self.layout.addLayout(input_layout)
        self.setLayout(self.layout)
        self.setWindowTitle("波斯历日期编辑")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
    window = Program()
    window.show()
    sys.exit(app.exec())

方案2:完整波斯历日历选择器

如果需要下拉日历也显示波斯历,得自定义QCalendarWidget或者用第三方的波斯历扩展库,这种方式需要自己实现波斯历的日历模型,复杂度更高,适合需要完整波斯历交互的场景。


内容的提问来源于stack exchange,提问作者ParsaTheH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:35:57