Frage

My app has a has a QTreeWidget that takes a QDate in one of its columns. Since the columns accept QVariants they can hold practically any kind of data. I've found that the TreeWidget must use the actual QDate objects instead of QStrings for the column sorting functionality to work correctly. If I use QStrings for dates, they won't sort in the proper chronological order but rather by the numerical values of the strings. (which is wrong!) My program supports several date formats: USA Style, European style, and ISO-8601 style. I would like to keep everything consistent throughout the app depending on which date format the user has chosen.

However, I noticed that QDate only displays dates in MM/DD/YYYY format. There's also a strange bug where the QDate displays MM/DD/YYYY on Windows but the exact same code displays MM/DD/YY on Linux. How can I get the QDate to show dates in YYYY/MM/DD or DD/MM/YYYY format without converting to a QString? It is essential to keep everything in QDate format so I don't break the column sort function in the QTreeWidget.

Here's my code that converts the QString to a QDate: (nextitem is a QStringList)

// Convert QString date to QDate to make it sort correctly
                QDate entrydate;
                QString id=nextitem.at(2);

                id=id.remove("/");


                QString datepattern;

                switch(Buffer::date_format){
                case 0: // European
                    datepattern="ddMMyyyy";
                    break;

                case 1: // USA Style
                    datepattern="MMddyyyy";
                    break;

                case 2: // ISO
                    datepattern="yyyyMMdd";
                    break;
                }


                entrydate=QDate::fromString(id,datepattern);
War es hilfreich?

Lösung

QDate follows the current settings in the operating system. If that setting happens to be MM/DD/YY, then that's what you'll get. Note: this is what the user wants. A uniform date format in all applications.

The setting is also influenced by the current locale settings in the OS. In the USA for example the default would be MM/DD/YY, while in most European countries it's DD/MM/YY.

In other words: don't worry about it. It's not a bug, it's a feature. And you shouldn't try to work around it. Users don't want their applications ignoring their system settings. If my system is set to display dates in MM/DD/YY, I certainly wouldn't want your app doing its own thing and showing me dates in YYYY/MM/DD format instead.

Andere Tipps

You can use this code:

QVariant var = item->data(i, Qt::DisplayRole);
if (var.type() == QVariant::DateTime)
{
    QDateTime dt = var.value<QDateTime>();
    QString value = dt.toString("yyyyMMdd");  // Or whatever format you need
}
else
    QString value = item->text(i);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top