QTableView formatting numbers

后端 未结 1 829
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 18:08

I have created a delegate and i\'m able to align and boldface the numbers on the table. I would like to force them to have two decimal places, for example 1.2 should show as 1.2

相关标签:
1条回答
  • 2021-01-21 18:37

    One possible solution is to create a custom QSqlTableModel class and override the QVariant QSqlTableModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const method.

    In the case of setting how it will be shown we use the Qt::DisplayRole role as a filter, and in case of changing the background color we will use the 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);
    }
    

    Output:

    0 讨论(0)
提交回复
热议问题