Search code examples
c++qtqt5qdatetime

How to change dateTimeFromText to only allow minutes%15 or disable manual text input?


I have extended QDateTimeEdit to do steps in intervals of 15 minutes by overwriting stepBy(int steps). So if a user scrolls up the minutes-section, the only choices they have are 0, 15, 30 and 45.

One problem appears if a user enters the dateTime manually, because then no validation takes place. I had a good look at: https://qt.gitorious.org/qt/qt/source/57756e72adf2081137b97f0e689dd16c770d10b1:src/gui/widgets/qdatetimeedit.cpp
but to be honest, the dateTimeFromText method was a bit overwhelming.

I also found: http://qt-project.org/doc/qt-5/qt.html#InputMethodHint-enum but still not sure if that is of any help.

Is there any easy way to only allow dateTimes that have a minutes-section of 0, 15, 30 or 45? Or can I alternatively disable manual input?


Solution

  • You can use dateTimeChanged slot to manually control if input is divisible by 15. Also you can update the element with one of the closest permitted values.

        if (dateTime.time().minute()%15 != 0) {
        QTime t(dateTime.time().hour(),dateTime.time().minute()-dateTime.time().minute()%15,dateTime.time().second());
        ui->dateTimeEdit->setTime(t);
    }