PDA

View Full Version : QDateEdit Month/Day Rollover



giverson
7th January 2008, 19:44
Playing with an idea for month/day rollovers using QDateEdit. I realize the StepEnabled function is unsafe and subject to change between versions of Qt. :D

The current version for this is 4.2.2.

What I need this to do is if you increment the month past 12, it will step to the next year. If you decrement it past 1, it will step to the previous year. Same for the date, steps to the next month and if necessary, the next year. There will be no min date or max date defined.

I'm just making sure that I didn't overlook something major (like an easy way to do this or a devastating bug) and looking for perhaps an easier or safer to do this.

Please keep in mind that C++ is not my primary language so please be easy on the little nuances that I'm probably screwing up, though pointing them out is never bad (makes me a better programmer).

What I ended up changing to create my custom widget...

###############################
in the header
###############################

class CustomQDateEdit : public QDateEdit
{
Q_OBJECT
public:
CustomQDateEdit(QWidget *parent = 0);
CustomQDateEdit(QDate &date, QWidget *parent = 0);
QDateTimeEdit::StepEnabled stepEnabled() const;
void stepBy(int steps);
};

##########################
in the source
##########################

CustomQDateEdit::CustomQDateEdit(QWidget *parent) : QDateEdit( parent)
{
}

CustomQDateEdit::CustomQDateEdit(QDate &date, QWidget *parent) : QDateEdit(date, parent)
{
}

//this effectively disables step checking on QDateEdits
//1 is a check for if it can step up, 2 is a check for if it can step down...or them together and get 3
//do not use this if you want min and max ranges defined...unless you want it wrapping
QDateTimeEdit::StepEnabled CustomQDateEdit::stepEnabled() const
{
return 3;
}

//custom stepBy...this allows rollover of months and years on QDateEdits
void CustomQDateEdit::stepBy(int steps)
{
QDate date(QDateEdit::date());
QDateEdit::Section temp_section = currentSection();
if(temp_section == QDateEdit::DaySection)
{
QDate next_date(date.addDays(steps));
if(next_date.month() != date.month() || next_date.year() != date.year())
{
QDateEdit::setDate(next_date);
steps = 0;
}
}
else if(temp_section == QDateEdit::MonthSection)
{
QDate next_date(date.addMonths(steps));
if(next_date.year() != date.year())
{
QDateEdit::setDate(next_date);
steps = 0;
}
}
QDateEdit::stepBy(steps);
}

This works, as far as I can tell...

jpn
7th January 2008, 19:57
One tiny little thing. I think you really should consider writing
QAbstractSpinBox::StepUpEnabled | QAbstractSpinBox::StepDownEnabled instead of "3" for the sake of readability and maintainability.