Search code examples
qtqt4qdatetime

QDateTimeEdit - Hour/Minutes sections resets to empty when focus is lost


I have a QDateTimeField with mask set as HH:mm Consider a scenario where user deletes (for example) hour section like this:

enter image description here

If user empties the hour section and subsequently press enter, hour section resets to 00 (which is the expected behavior, always).

enter image description here

If user empties the hour section and just click somewhere else (when QDateTimeField loses it's focus), hour section remains empty, which is my problem.

enter image description here

Can anyone hint me with a way to tackle this problem?


Solution

  • interpretText() function does the trick. You have to call interpretText() of the QDateTimeEditor in the setModelData function (in your delegate class) before accessing its text.

    According to Qt documentation

    This function interprets the text of the spin box. If the value has changed since last interpretation it will emit signals.

    Example:

    void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                       const QModelIndex &index) const
    {
        QDateTimeEdit *dateTime = static_cast<QDateTimeEdit*>(editor);
        dateTime->interpretText();
        model->setData(index, dateTime->text(), Qt::EditRole);
    }