qcalendarwidget.cpp

来自「QT 开发环境里面一个很重要的文件」· C++ 代码 · 共 2,019 行 · 第 1/4 页

CPP
2,019
字号
    Q_Q(QCalendarWidget);    m_model->showMonth(year, month);    updateHeader();    emit q->currentPageChanged(year, month);    m_view->internalUpdate();    update();    updateMonthMenu();}void QCalendarWidgetPrivate::updateHeader(){    monthButton->setText(QDate::longMonthName(m_model->shownMonth));    yearButton->setText(QString::number(m_model->shownYear));    yearEdit->setValue(m_model->shownYear);    QFontMetrics fm = monthButton->fontMetrics();    monthButton->setMaximumWidth(fm.boundingRect(QDate::longMonthName(m_model->shownMonth)).width() +        fm.boundingRect(QChar('y')).width());    fm = yearButton->fontMetrics();    yearButton->setMaximumWidth(fm.boundingRect(QString("55555")).width());}void QCalendarWidgetPrivate::update(){    QDate currentDate = m_model->date;    int row, column;    m_model->cellForDate(currentDate, &row, &column);    QModelIndex idx;    m_selection->clear();    if (row != -1 && column != -1) {        idx = m_model->index(row, column);        m_selection->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent);    }}void QCalendarWidgetPrivate::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const{    Q_Q(const QCalendarWidget);    q->paintCell(painter, rect, date);}void QCalendarWidgetPrivate::_q_slotChangeDate(const QDate &date, bool changeMonth){    QDate oldDate = m_model->date;    m_model->setDate(date);    QDate newDate = m_model->date;    if (changeMonth)        showMonth(newDate.year(), newDate.month());    if (oldDate != newDate) {        update();        Q_Q(QCalendarWidget);        emit q->selectionChanged();    }}void QCalendarWidgetPrivate::_q_editingFinished(){    Q_Q(QCalendarWidget);    emit q->activated(m_model->date);}/*!    \class QCalendarWidget    \brief The QCalendarWidget class provides a monthly based    calendar widget allowing the user to select a date.    \since 4.2    \image cleanlooks-calendarwidget.png    The widget is initialized with the current month and year, but    QCalendarWidget provides several public slots to change the year    and month that is shown.  The currently displayed month and year    can be retrieved using the currentPageMonth() and currentPageYear()    functions, respectively.    By default, today's date is selected, and the user can select a    date using both mouse and keyboard. The currently selected date    can be retrieved using the selectedDate() function. It is    possible to constrain the user selection to a given date range by    setting the minimumDate and maximumDate properties.    Alternatively, both properties can be set in one go using the    setDateRange() convenience slot. Set the \l selectionMode    property to NoSelection to prohibit the user from selecting at    all. Note that a date also can be selected programmatically using    the setSelectedDate() slot.    A newly created calendar widget uses abbreviated day names, and    both Saturdays and Sundays are marked in red. The calendar grid is    not visible. The week numbers are displayed, and the first column    day is Sunday.    The notation of the days can be altered to a single letter    abbreviations ("M" for "Monday") by setting the    horizontalHeaderFormat property to    QCalendarWidget::SingleLetterDayNames. Setting the same property    to QCalendarWidget::LongDayNames makes the header display the    complete day names. The week numbers can be removed by setting    the verticalHeaderFormat property to    QCalendarWidget::NoVerticalHeader.  The calendar grid can be    turned on by setting the gridVisible property to true using the    setGridVisible() function:    \table    \row \o        \image qcalendarwidget-grid.png    \row \o        \code            QCalendarWidget *calendar;            calendar->setGridVisible(true);        \endcode    \endtable    Finally, the day in the first column can be altered using the    setFirstDayOfWeek() function.    The QCalendarWidget class also provides three signals,    selectionChanged(), activated() and currentPageChanged() making it    possible to respond to user interaction.    The rendering of the headers, weekdays or single days can be    largely customized by setting QTextCharFormat's for some special    weekday, a special date or for the rendering of the headers.    Only a subset of the properties in QTextCharFormat are used by the    calendar widget. Currently, the foreground, background and font    properties are used to determine the rendering of individual cells    in the widget.    \sa QDate, QDateEdit, QTextCharFormat*//*!    \enum QCalendarWidget::SelectionMode    This enum describes the types of selection offered to the user for    selecting dates in the calendar.    \value NoSelection      Dates cannot be selected.    \value SingleSelection  Single dates can be selected.    \sa selectionMode*//*!    Constructs a calendar widget with the given \a parent.    The widget is initialized with the current month and year, and the    currently selected date is today.    \sa setCurrentPage()*/QCalendarWidget::QCalendarWidget(QWidget *parent)    : QWidget(*new QCalendarWidgetPrivate, parent, 0){    Q_D(QCalendarWidget);    setAutoFillBackground(true);    setBackgroundRole(QPalette::Window);    QVBoxLayout *layoutV = new QVBoxLayout(this);    layoutV->setMargin(0);    d->m_model = new QCalendarModel(this);    QTextCharFormat fmt;    fmt.setForeground(QBrush(Qt::red));    d->m_model->m_dayFormats.insert(Qt::Saturday, fmt);    d->m_model->m_dayFormats.insert(Qt::Sunday, fmt);    d->m_view = new QCalendarView(this);    d->m_view->setObjectName("qt_calendar_calendarview");    d->m_view->setModel(d->m_model);    d->m_model->setView(d->m_view);    d->m_view->setSelectionBehavior(QAbstractItemView::SelectItems);    d->m_view->setSelectionMode(QAbstractItemView::SingleSelection);    d->m_view->horizontalHeader()->setResizeMode(QHeaderView::Stretch);    d->m_view->horizontalHeader()->setClickable(false);    d->m_view->verticalHeader()->setResizeMode(QHeaderView::Stretch);    d->m_view->verticalHeader()->setClickable(false);    d->m_selection = d->m_view->selectionModel();    d->createHeader(this);    d->m_view->setFrameStyle(QFrame::NoFrame);    d->m_delegate = new QCalendarDelegate(d, this);    d->m_view->setItemDelegate(d->m_delegate);    d->update();    d->updateHeader();    setFocusPolicy(Qt::StrongFocus);    setFocusProxy(d->m_view);    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);    connect(d->m_view, SIGNAL(changeDate(QDate,bool)),            this, SLOT(_q_slotChangeDate(QDate,bool)));    connect(d->m_view, SIGNAL(clicked(QDate)),            this, SIGNAL(clicked(QDate)));    connect(d->m_view, SIGNAL(editingFinished()),            this, SLOT(_q_editingFinished()));    connect(d->prevMonth, SIGNAL(clicked(bool)),            this, SLOT(_q_prevMonthClicked()));    connect(d->nextMonth, SIGNAL(clicked(bool)),            this, SLOT(_q_nextMonthClicked()));    connect(d->yearButton, SIGNAL(clicked(bool)),            this, SLOT(_q_yearClicked()));    connect(d->monthMenu, SIGNAL(triggered(QAction*)),            this, SLOT(_q_monthChanged(QAction*)));    connect(d->yearEdit, SIGNAL(editingFinished()),            this, SLOT(_q_yearEditingFinished()));    layoutV->setMargin(0);    layoutV->setSpacing(0);    layoutV->addWidget(d->headerBackground);    layoutV->addWidget(d->m_view);}/*!   Destroys the calendar widget.*/QCalendarWidget::~QCalendarWidget(){}/*!   \reimp*/QSize QCalendarWidget::sizeHint() const{    return minimumSizeHint();}/*!   \reimp*/QSize QCalendarWidget::minimumSizeHint() const{    Q_D(const QCalendarWidget);    ensurePolished();    int w = 0;    int h = 0;    int end = 53;    int rows = 7;    int cols = 8;    int startRow = 0;    int startCol = 0;    const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) * 2;    if (horizontalHeaderFormat() == QCalendarWidget::NoHorizontalHeader) {        rows = 6;        startRow = 1;    } else {        for (int i = 1; i <= 7; i++) {            QFontMetrics fm(d->m_model->formatForCell(0, i).font());            w = qMax(w, fm.width(d->m_model->dayName(i)) + marginH);            h = qMax(h, fm.height());        }    }    if (verticalHeaderFormat() == QCalendarWidget::NoVerticalHeader) {        cols = 7;        startCol = 1;    }    QFontMetrics fm(d->m_model->formatForCell(1, 1).font());    for (int i = 1; i <= end; i++) {        w = qMax(w, fm.width(QString::number(i)) + marginH);        h = qMax(h, fm.height());    }    if (d->m_view->showGrid()) {        // hardcoded in tableview        w += 1;        h += 1;    }    w += 1; // default column span    h = qMax(h, d->m_view->verticalHeader()->minimumSectionSize());    w = qMax(w, d->m_view->horizontalHeader()->minimumSectionSize());    //add the size of the header.    QSize headerSize(0, 0);    if (d->headerVisible) {        int headerH = d->headerBackground->sizeHint().height();        int headerW = 0;        headerW += d->prevMonth->sizeHint().width();        headerW += d->nextMonth->sizeHint().width();        QFontMetrics fm = d->monthButton->fontMetrics();        int monthW = 0;        for (int i = 1; i < 12; i++)            monthW = qMax(monthW, fm.boundingRect(QDate::longMonthName(i)).width());        monthW += fm.boundingRect(QChar('y')).width();        headerW += monthW;        fm = d->yearButton->fontMetrics();        headerW += fm.boundingRect(QString("55555")).width();        headerSize = QSize(headerW, headerH);    }    w *= cols;    w = qMax(headerSize.width(), w);    h = (h * rows) + headerSize.height();    return QSize(w , h);}/*!    Paints the cell specified by the given \a date, using the given \a painter and \a rect.*/void QCalendarWidget::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const{    Q_D(const QCalendarWidget);    d->m_delegate->paintCell(painter, rect, date);}/*!    \property QCalendarWidget::selectedDate    \brief the currently selected date.    The selected date must be within the date range specified by the    minimumDate and maximumDate properties. By default, the selected    date is the current date.    \sa setDateRange()*/QDate QCalendarWidget::selectedDate() const{    Q_D(const QCalendarWidget);    return d->m_model->date;}void QCalendarWidget::setSelectedDate(const QDate &date){    Q_D(QCalendarWidget);    if (d->m_model->date == date && date == d->getCurrentDate())        return;    if (!date.isValid())        return;    d->m_model->setDate(date);    d->update();    QDate newDate = d->m_model->date;    d->showMonth(newDate.year(), newDate.month());}/*!    Returns the year of the currently displayed month. Months are     numbered from 1 to 12.    \sa monthShown(), setCurrentPage()*/int QCalendarWidget::yearShown() const{    Q_D(const QCalendarWidget);    return d->m_model->shownYear;}/*!    Returns the currently displayed month. Months are numbered from 1 to     12.    \sa yearShown(), setCurrentPage()*/int QCalendarWidget::monthShown() const{    Q_D(const QCalendarWidget);    return d->m_model->shownMonth;}/*!    Displays the given \a month of the given \a year without changing    the selected date. Use the setSelectedDate() function to alter the    selected date.    The currently displayed month and year can be retrieved using the    currentPageMonth() and currentPageYear() functions respectively.    \sa yearShown(), monthShown(), showPreviousMonth(), showNextMonth(),    showPreviousYear(), showNextYear()*/void QCalendarWidget::setCurrentPage(int year, int month){    Q_D(QCalendarWidget);    d->showMonth(year, month);}/*!    Shows the next month relative to the currently displayed    month. Note that the selected date is not changed.    \sa showPreviousMonth(), setCurrentPage(), setSelectedDate()*/void QCalendarWidget::showNextMonth(){    int year = yearShown();    int month = monthShown();    if (month == 12) {        ++year;        month = 1;    } else {        ++month;    }    setCurrentPage(year, month);}/*!    Shows the previous month relative to the currently displayed    month. Note that the selected date is not changed.    \sa showNextMonth(), setCurrentPage(), setSelectedDate()*/void QCalendarWidget::showPreviousMonth(){    int year = yearShown();    int month = monthShown();    if (month == 1) {        --year;        month = 12;    } else {        --month;    }    setCurrentPage(year, month);}/*!    Shows the currently displayed month in the \e next year relative    to the currently displayed year. Note that the selected date is    not changed.    \sa showPreviousYear(), setCurrentPage(), setSelectedDate()*/void QCalendarWidget::showNextYear(){    int year = yearShown();    int month = monthShown();    ++year;    setCurrentPage(year, month);}/*!    Shows the currently displayed month in the \e previous year    relative to the currently displayed year. Note that the selected    date is not changed.    \sa showNextYear(), setCurrentPage(), setSelectedDate()*/void QCalendarWidget::showPreviousYear(){    int year = yearShown();    int month = monthShown();    --year;    setCurrentPage(year, month);}/*!    Shows the month of the selected date.    \sa selectedDate(), setCurrentPage()*/void QCalendarWidget::showSelectedDate(){    QDate currentDate = selectedDate();    setCurrentPage(currentDate.year(), currentDate.month());}/*!    Shows the month of the today's date.    \sa selectedDate(), setCurrentPage()*/void QCalendarWidget::showToday(){    QDate currentDate = QDate::currentDate();    setCurrentPage(currentDate.year(), currentDate.month());}/*!    \property QCalendarWidget::minimumDate    \brief the minimum date of the currently specified date range.    The user will not be able to select a date that is before the    currently set minimum date.    \table    \row    \o \image qcalendarwidget-minimum.png    \row    \o    \code    QCalendarWidget *calendar;    calendar->setGridVisible(true);    calendar->setMinimumDate(QDate(2006, 6, 19));    \endcode    \endtable

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?