Set date at QDateEdit with C++

15,841

Solution 1

First, the docs indicate that the QDateEdit object has parameterized constructor that permits the date to be initialized on construction:

QDateEdit::QDateEdit ( const QDate & date, QWidget * parent = 0 )

Depending upon how you have instantiated your QDateEdit object, you might also consider subclassing QDateEdit with your own widget, and the setting up the QDateEdit object in your widget's constructor. This method may overkill, though (without code, it's tough to speculate what is best...)

The edited question provides more to go on. The QDateEdit docs indicate that a QDateEdit method accepts a QDate object, not a QString object. So your function should appear something more like:

void form_dialog::setCurrentDate()
{
    QDate date = QDate::currentDate();
    ui->DateEdit->setDate(date);
}

Note that your compiler is reporting the mismatched object types in the error message above.

Solution 2

If you want to show the current date when your dialog comes up, I would do the following:

  • handle the dialog's show event,
  • get the current date,
  • set current date to the date edit widget.

For example:

void MyDialog::showEvent(QShowEvent * event)
{
    QDate date = QDate::currentDate();
    m_dateEdit->setDate(date); // sets the current date to date edit.

    QDialog::showEvent(event);
}
Share:
15,841
SjonTeflon
Author by

SjonTeflon

A Applied Physics Student at University of Technology Delft.

Updated on June 15, 2022

Comments

  • SjonTeflon
    SjonTeflon almost 2 years

    I have this QDateEdit widget but it displays always a standard time like 01-01-2014 (in DD-MM-YYYY, but I can change this in the UI). But I want it to display the current time if the dialog (where this QDateEdit widget is) is opened. I tested this just on a label (see the void form_dialog). But its printss out "sa nov 23 2013". But I want it like 23-11-2013. Also it gives me an error :

    QDateTimeEdit::setDate' : cannot convert parameter 1 from 'QString' to 'const QDate &'
    Reason: cannot convert from 'QString' to 'const QDate'
    No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
    

    So

    void form_dialog::setCurrentDate()
    {
        QDate date = QDate::currentDate();
        QString dateString = date.toString();
        ui->DateEdit->setDate(dateString);
    }
    

    Thanks!

    Maybe its usefull to have something visual, the widget that is displayed below should display the current date:
    enter image description here