⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

Changed date is not shown in QStandardItemModel

  • Hi,
    I created an date editor in QDelegate CreateEditor like this:

                QDateEdit *deditor = new QDateEdit(parent);
                deditor->setDisplayFormat ("MM/dd/yyyy");
                deditor->setCalendarPopup (true);
                deditor->setStyleSheet ("background-color:rgb(255,217,229)");
                connect(deditor,&QDateEdit::editingFinished ,this,&myDelegate::commitAndCloseEditor );

    In setEditorData I have

        QDateEdit *dateEditor = qobject_cast<QDateEdit*>(editor);
                dateEditor->setDate (index.model ()->data (index, Qt::EditRole).toDate ());
                QVariant d(index.data (Qt::DisplayRole));
                QDate fixdate;
                fixdate = d.toDate ();
                qDebug() << "fixdate: ";

    In setModelData:

                QDateEdit *dateEdit = qobject_cast<QDateEdit*>(editor);
                QModelIndex updateIndex(index.model ()->index(index.row (),0,index.parent ()));
                QString fixID;
                QVariant v(updateIndex.data (Qt::DisplayRole));
                fixID = v.toString ();
                qDebug() << "FixID: " << fixID;
                model->setData (index,dateEdit->date ().toString ("MM/dd/YYYY"));

    I get the following message in output:
    FixID: "3"
    When I change the date in the editor it changes the month and the day but writes YYYY as a year. What did I miss?
    Thank you.

  • Lifetime Qt Champion

    Is it correct that in setEditorData , you use
    setDate (index.model ()->data (index, Qt::EditRole) <<< Edit role
    but for data, you use
    d(index.data (Qt::DisplayRole)); << Display role

    Just a thought.

  • Hi @mrjj
    I changed it to

         dateEditor->setDate (index.model ()->data (index, Qt::EditRole).toDate ());
                QVariant d(index.data (Qt::EditRole));

    but the same thing happens.

  • @mrjj
    Even the QVariant is missing the year:

    QVariant:  QVariant(QString, "01/01/YYYY")

  • Lifetime Qt Champion

    You mean its truncated and only the last / is there but no "YYYY" or
    what is missing?
    If you use pure string ( not as date) does it work then?
    Im not sure if save/load data that is wrong og some convert to/from string with datatime.

  • Lifetime Qt Champion


    Your format is wrong: it's yyyy in lower case.

  • You should actually store the date as a QDate rather than a string and let displayText() in the delegate to take care to display it in the correct format

  • I will change it from text to date. Thank you.

Log in to reply