QLocale setDefault only works at 2nd time called

1.1k Views Asked by At

I am trying to change the default language of a QLocale variable in my code and then use the different separators of each language. I do not want to change it for the whole system I just want to have a chance to print numbers with different group- and decimal separators. The user can change the Decimal separator to what he or she prefers.

//this part works as expected in debugger
QLocale locale;

if(decSep==".")
{
    locale.setDefault(QLocale::English); 
}
else if(decSep==",")
{
    locale.setDefault(QLocale::German);
}
else
{
    locale.setDefault(QLocale::system().language());
}

//added for debug purposes
/*if(local.language()==QLocale::English)
{
    int x=0;//jumped here when it was supposed to do so (decSep==".")
}*/

Now there is some code which I'm sure has nothing to do with this error. Later I use:

//Now this doesn't work

QString tempNum1 = locale.toString(myNum, 'f');

With locale.toString I get the separators default to the given language.

Now my problem is that the locale variable seems to need some time or smth to change to other settings. When I change the decSep var and therefore the language is changed (I debugged this, this part is changed and when I ask for the language it gives the right enum) it uses the previously set settings. When I then call the function again, which gives me the tempNum1 string then it is working.

Is this a known problem or am I doing something wrong? Can I somehow updated locale or something like that?

1

There are 1 best solutions below

0
On BEST ANSWER

You are setting the default locale, not the language of the current QLocale object.

Note that setDefault is a static function and therefore it does not change the object properties itself, i.e.

locale.setDefault(QLocale::English)

is the same as

QLocale::setDefault(QLocale::English)

Example

The following example may clarify this behaviour:

QLocale locale;
QLocale localeGerman(QLocale::German);
qDebug() << locale.toString(1.234, 'f'); // returns 1.234
qDebug() << localeGerman.toString(1.234, 'f'); // returns 1,234
QLocale::setDefault(QLocale::German); // same as locale.setDefault(QLocale::German);
qDebug() << locale.toString(1.234, 'f'); // returns still 1.234
QLocale locale2;
qDebug() << locale2.toString(1.234, 'f'); // returns 1,234
locale = localeGerman;
qDebug() << locale.toString(1.234, 'f'); // returns 1,234