Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set precision and alignment for displaying numeric values in QTableView

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:

  • double 12.00 will be shown as 12,
  • double 12.10 will be shown as 12.1,
  • double 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.

like image 398
murison Avatar asked Sep 29 '22 10:09

murison


1 Answers

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();
}
like image 129
Walt Dizzy Records Avatar answered Oct 03 '22 08:10

Walt Dizzy Records