Formatting numbers in QTableView [SOLVED]
-
Hello,
I have a QTableView that is populated by a QSqlQueryModel. The data in the model has columns that must be formatted this way: "#,##0.00". Is it possible to format some columns without subclassing the model or the widget? The QTableView would be read-only so there is no editing needed. The values would have to be retrieved though.
This is how I usually populate a QTableView:
@
QSqlQuery query;
query.prepare("SELECT * FROM tcustomer");
query.exec();
QSqlQueryModel model;
model.setQuery(query);
ui->tableView->setModel(model);
@ -
Hi,
Maybe you could use a custom "delegate":http://qt-project.org/doc/qt-5.0/qtwidgets/qstyleditemdelegate.html to define the display you like and then add it only to the columns you want.
-
Thank you.
I used QStyledItemDelegate. Here is what I did:
numberformatdelegate.h
@
#ifndef NUMBERFORMATDELEGATE_H
#define NUMBERFORMATDELEGATE_H#include <QStyledItemDelegate>
class NumberFormatDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit NumberFormatDelegate(QObject *parent = 0);
virtual QString displayText(const QVariant &value, const QLocale &locale) const;signals:
public slots:
};
#endif // NUMBERFORMATDELEGATE_H@
numberformatdelegate.cpp
@#include "numberformatdelegate.h"NumberFormatDelegate::NumberFormatDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}QString NumberFormatDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
QString formattedNum = locale.toString(value.toDouble(), 'f', 2);
return formattedNum;
}
@To use it on a tableview:
@
ui->tableView->setItemDelegateForColumn(3, new NumberFormatDelegate(this));
@ -
Great, don't forget to edit your post and add [solved] :-)