QDateEdit strange behaviour while setting minimumDate
-
Topic title is obscure, but i'll try to clarify it.
I'm trying to set QDateEdit's minimum date to one day BEFORE the particular date. It works fine until one day decrement leads to year change. When i click decrement control of QDateEdit, nothing changes. I can manually type "31.12.1929", but control is not working.
#include <QApplication> #include <QDate> #include <QDateEdit> int main(int argc, char *argv[]) { QApplication a(argc, argv); QDateEdit *date_edit = new QDateEdit(); QDate date(1930,01,01); QDate prev_date = date.addDays(-1); date_edit->setMinimumDate(prev_date); date_edit->setDate(date); date_edit->show(); return a.exec(); }
I'm using prebuilt Qt 5.5.1 x32 on windows 8.1 with a msvc2012 compiler.
-
I needed a QDateEdit that allows me to set minimum date, and check if field is empty. QDateEdit must be empty when widget appears and user can set QDateEdit to empty using spinbox buttons. For example:
minimum date = "1930.01.01" visualize field as empty when date is "1929.12.31"
I think, i have found a solution by subclassing QDateEdit and reimplementing mousePressEvent() function. Not most elegant solution, but at least it works for me for now.
//dateedit.h #ifndef DATEEDIT_H #define DATEEDIT_H #include <QObject> #include <QDateEdit> #include <QMouseEvent> class DateEdit : public QDateEdit { public: DateEdit(const QDate max_date, const QDate min_date, QWidget *parent = 0); private: void mousePressEvent(QMouseEvent * event); QDate min_date_; // user defined minimum value to show QDate special_value_date_; // real minimum value to show "00.00.0000" text }; #endif // DATEEDIT_H
//dateedit.cpp #include <QRect> #include <QDebug> #include <QStyleOptionSpinBox> #include "dateedit.h" DateEdit::DateEdit(const QDate max_date, const QDate min_date, QWidget *parent) : QDateEdit(parent) { setMaximumDate(max_date); min_date_ = min_date; special_value_date_ = min_date.addDays(-1); setMinimumDate(special_value_date_); setSpecialValueText("00.00.0000"); setDate(special_value_date_); } void DateEdit::mousePressEvent(QMouseEvent *event) { int flag = 0; QStyleOptionSpinBox opt; this->initStyleOption(&opt); QRect rect = this->style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxUp); if(rect.contains(event->pos())) { if(date() == special_value_date_){ setDate(min_date_); flag = 1; } } else { if(date() == min_date_){ setDate(special_value_date_); } } if(flag == 0) { // avoid incrementing date twice QAbstractSpinBox::mousePressEvent(event); event->accept(); } }
-
What I would do is start from scratch. Build a widget with a line edit and two buttons, apply a date validator to the line edit and implement the increment-decrement functionality of the buttons. It's easier done than said.
Also, take a look at https://api.kde.org/frameworks/kwidgetsaddons/html/classKDatePicker.html
-
Thanks. I'll take a look.