QTableView格式化数字

QTableView formatting numbers

我已经创建了一个代表,我可以对齐 table 上的数字并将其加粗。我想强制他们有两位小数,例如 1.2 应该显示为 1.20。 这是delagete的header:

#ifndef TOTALDELEGATE_H
#define TOTALDELEGATE_H

#include <QObject>
#include <QStyledItemDelegate>


class TotalDelegate : public QStyledItemDelegate
{
public:
  TotalDelegate();

  virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
};

#endif // TOTALDELEGATE_H

实现如下:

#include "totaldelegate.h"

TotalDelegate::TotalDelegate()
{

}

void TotalDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
  if(!index.isValid()) return;
  QFont font=option.font;
  font.setBold(true);

  QStyleOptionViewItem localOption(option);
  localOption.font=font;
  localOption.displayAlignment=Qt::AlignRight;
  QStyledItemDelegate::paint(painter,localOption,index);

}

对于如何控制对齐仍然有点迷茫,所以它强制保留两位小数。我也想知道如何更改背景颜色。 谢谢您的帮助。 这是模型:

  body = new QSqlTableModel(parent,data->m_db);
  body->setTable("C"+QString::number(markTime.toSecsSinceEpoch()));
  body->select();
  ui->bodyView->setModel(body);
  ui->bodyView->sortByColumn(0,Qt::AscendingOrder);
  ui->bodyView->setColumnWidth(0,30);
  ui->bodyView->setColumnWidth(1,80);
  for(int x=2;x<ui->columns->maximum()+2;x++) ui->bodyView->setColumnWidth(x,40);
  ui->bodyView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  ui->bodyView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  ui->bodyView->setAlternatingRowColors(true);

//  //  ***************  Testing  ********************
  ui->bodyView->setItemDelegateForRow(10,new TotalDelegate);

//  //  *****************Testing  ********************

  ui->bodyView->show();

一种可能的解决方案是创建自定义 QSqlTableModel class 并覆盖 QVariant QSqlTableModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const 方法。

在设置显示方式的情况下,我们使用 Qt::DisplayRole 角色作为过滤器,在更改背景颜色的情况下,我们将使用 Qt::BackgroundRole:

*.h

#ifndef CUSTOMSQLTABLEMODEL_H
#define CUSTOMSQLTABLEMODEL_H

#include <QSqlTableModel>

class CustomSqlTableModel : public QSqlTableModel
{
public:
    CustomSqlTableModel(QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase());

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
};

#endif // CUSTOMSQLTABLEMODEL_H

*.cpp

#include "customsqltablemodel.h"

#include <QBrush>

CustomSqlTableModel::CustomSqlTableModel(QObject *parent, QSqlDatabase db):QSqlTableModel(parent, db)
{

}

QVariant CustomSqlTableModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole){
        if(index.column()  == 4)
            return QVariant(QString::number(QSqlTableModel::data(index, role).toDouble(), 'f', 2));
    }

    if (role == Qt::BackgroundRole){
        if(index.row()  == 4)
            return QVariant(QBrush(Qt::blue));
    }
    return QSqlTableModel::data(index, role);
}

输出: