Restrict qDateTimeEdit to 15 minutes

2019-07-22 16:38发布

问题:

In http://qt-project.org/doc/qt-5/qabstractspinbox.html#specialValueText-prop there is an example of how to restrict a QSpinBox. It says:

  zoomSpinBox->setSingleStep(10);

My problem is that I would like to have a QDateTimeEdit where the user can only specify date times by quarter hours aka 15 minutes.

Like 2014-12-12 12:30:00 is valid and possible but 2014-12-12 12:10:00 is not.

Is there any easy way to accomplish this, as I couldn't find a way.

One rather complicated solution would be to validate the user's input and round it to the next quarter hour, but that is something I would like to avoid because I find it to be too disguised/obscure for the user. (Like when he enters 12:05 and it updates to 12:15 without him actually seeing it...)

回答1:

One way would be to overwrite

 QDateTimeEdit::stepBy(int steps)

check if the current section as returned by currentSection() is the minute section and in/decrement the DateTime in steps of 15min. Of course you still have to overwrite QDateTimeEdit::dateTimeFromText to fix dates typed in.



回答2:

setSingleStep(10); doesn't provide validation,it is just step and when user types another numbers, spinbox accepts this data. So you can show the user that he enters wrong data and you expect something another.

For example:

void MainWindow::on_dateTimeEdit_dateTimeChanged(const QDateTime &dateTime)
{
    if(dateTime.time().minute() % 15 != 0)
    {
        ui->dateTimeEdit->setStyleSheet("background-color: red");
        QApplication::beep();//maybe
    }
    else
        ui->dateTimeEdit->setStyleSheet("");
}

Wrong:

Correct(0,15,30,45):



标签: c++ qt qt5