简体   繁体   中英

Can I change default formatting for QDate::QString()?

QT's QDate::toString() function, without parameters, converts a QDate to a QString with a default format of "ddd MMM d yyyy". Our application is international and this fixed format does not reflect locale and regional settings. I don't want to use LongFormat because it takes too much space; the default no-parameter is a more optimal length. I have obtained the LongFormat from system QLocale massaged the format string to give us a QString similar to the default format but also reflects international settings.

Is there any way I can tell QT to use my new formatting string whenever toString() is called so that I don't have to find all existing toString() calls and insert the formatting string as a parameter?

According to the Qt documentation of QDate , you can specify the format you desire in QDate::toString() .

Now, to avoid the repetitions that are bothering you, you can specify somewhere a static variable that contains the application formatting. Then you give it as parameter everytime you call QDate::toString() . This way, you will have to use always the same variable/format.


But if you really want to not give any parameters, the solution is to subclass QDate and redefine the toString() method by changing the default format by the one you want.

For example:

.h :

class MyDate final : public QDate
{
    private:
        static QString my_format;

    public:
        MyDate();
        MyDate(int y, int m, int d);
        MyDate(const QDate & date);

        QString toFormattedString() const;
};

.cpp :

QString MyDate::my_format = "yyyy - MMMM dddd dd"; // Specify the format you desire.

MyDate::MyDate() : QDate()
{}
MyDate::MyDate(int y, int m, int d) : QDate(y, m, d)
{}
MyDate::MyDate(const QDate & date) : QDate(date)
{}
QString MyDate::toFormattedString() const
{
    return toString(my_format);
}

And you can you it as follows (example):

MyDate md(QDate::currentDate());
qDebug() << md.toFormattedString();

Here I have named the method toFormattedString() in order to make the code more understandable. Feel free to adapt it as you want.

I hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM