PDA

View Full Version : QAbstractItemModel, QTableWidget. Decimal point.



shestero
18th July 2014, 18:16
In float and double values displayed in QTableWidget connected to QAbstractItemModel I want to display comma instead of international decimal point.
How can I do it?

anda_skoa
18th July 2014, 20:16
So you are running the program in a locale setting that has point as the decimal separator?
Do you want that only in a specific table or througout the whole program?

Cheers,
_

shestero
18th July 2014, 23:04
I would be glad for the both answers but especially for the specific table case.
I tried: http://www.qtcentre.org/threads/53127-Override-locale-with-QSystemLocale (code from the last post, but with comma).

anda_skoa
19th July 2014, 09:26
Floating point numbers are usually formatted according to the locale of the user, e.g. using a point in countries where this is common and a comma in those which use that separator.

An application can of course override this, e.g. if it provides its own locale settings.

If you only need it in a particular case, you can use QLocale::toString() on a specifically created QLocale object.
In your case using an item delegate for that cell, column/row or whole table, or by overriding the model's data to return a different string for the respective cells' DisplayRole.

Cheers,
_

shestero
19th July 2014, 12:30
thank you. Following code solves my task:
class DoubleDelegate: public QStyledItemDelegate
{
Q_OBJECT
public:

DoubleDelegate(QObject* parent=0) : QStyledItemDelegate(parent) { }
virtual ~DoubleDelegate() { }

virtual QString displayText(const QVariant &value, const QLocale &locale) const
{
if (value.type() == QVariant::Double) {
return QString().sprintf("%.2f", value.toDouble()).replace('.',',');
}
return QStyledItemDelegate::displayText(value, locale);
}
};

d_stranz
23rd July 2014, 19:11
If you want your code to show properly formatted doubles no matter what locale, then you should do this:



class DoubleDelegate: public QStyledItemDelegate
{
Q_OBJECT
public:

DoubleDelegate(QObject* parent=0) : QStyledItemDelegate(parent) { }
virtual ~DoubleDelegate() { }

virtual QString displayText(const QVariant &value, const QLocale &locale) const
{
if (value.type() == QVariant::Double) {
return locale.toString( value.toDouble(), 'f', 2 );
}
return QStyledItemDelegate::displayText(value, locale);
}
};


Your original code will substitute a comma for a period in all cases, regardless of locale. Maybe that's what you want to do, but an American will certainly be confused seeing a table where the entries are all of the form "123,45".