What would be the easiest way to set fixed format to display numeric values in QTableView? I need to format as currency - so always show decimal part separator and 2 digits after it. Possibly align righ, maybe append a currency name. Right now it shows as much as needed, eg:
12.00
will be shown as 12
, 12.10
will be shown as 12.1
, 12.11
will be shown as 12.11
,Is there an easy way to go? SetFormatForColumn or something like that? Can't finde enything really useful over that subject in the doc...
At the moment I have subclassed QStyledItemDelegate
. This works, but seems like a huge overhead, as only thing that my subclass does is reimplement 2 methods - as below:
QString CurrencyDelegate::displayText(const QVariant & value, const QLocale & locale) const {
return locale.toCurrencyString(value.toDouble());
}
void CurrencyDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const {
QStyleOptionViewItem myOption = option;
(myOption.displayAlignment ^= Qt::AlignLeft) |= Qt::AlignRight;
QStyledItemDelegate::paint(painter, myOption, index);
}
Is there an easier way? Any help appreciated.
Return a QString
from QAbstractItemModel::data
using QString::number
QVariant YourTableModel::data(const QModelIndex & index, int32_t role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
switch (index.column())
{
case YOUR_COL:
double theDouble = getDoubleFromModelSomewhere();
return QString::number(theDouble, 'f', 2); // Format shows 2 decimals
}
}
return QVariant();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With