How to change the cell text color in a QTableView?

I've tried this (without success):


ui->tableView->model()->setData(ui->tableView->model()->index(5, 5, QModelIndex()), QVariant(QColor(Qt::red)), Qt::DecorationRole);

Thanks in advance.
How to change the cell text color in a QTableView

Use: Qt::ForegroundRole - http://qt-project.org/doc/qt-5.0/qtcore/qt.html#ItemDataRole-enum
Qt::ForegroundRole also doesn't work, even Qt::BackgroundColorRole doesn't work. There is anything else to be done? May be some kind of update?

The model is a QSqlTableModel.
The model is a QSqlTableModel.

In that case you'll either have to subclass or use a delegate.

From the Qt5 source code:
1
2
3
4
5
6
QVariant QSqlTableModel::data(const QModelIndex &index, int role) const
{
    Q_D(const QSqlTableModel);
    if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::EditRole))
        return QVariant();
. . .


http://qt.gitorious.org/qt/qtbase/blobs/stable/src/sql/models/qsqltablemodel.cpp#line470

Ok, something is working now. Here is what it becomes

1
2
3
4
5
6
7
8
9
10
11
QVariant MySqlTableModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlTableModel::data(index, role);
    if (role == Qt::TextColorRole && index.column() == 1)
    {
//        double d = value.toDouble();
//        if(d > 0)
            return QVariant::fromValue(QColor(Qt::blue));
    }
    return value;
}


Next step is to check the value, like in the commented lines. Which approach could be taken for that?

Thanks in advance.
It seems that the value could be retrieved with

double d = this->record(index.row()).value(index.column()).toDouble();
Last edited on
try this:
1
2
3
4
5
6
7
8
9
10
QVariant MyTableModel::data(const QModelIndex &index, int role) const {
    if (role == Qt::ForegroundRole && index.column() == 1)   {  // notice that Qt::TextColorRole is deprecated
        QVariant value = QSqlTableModel::data(index, Qt::DisplayRole);
        QVariant value = index.data(); // the data is in DisplayRole
        double d = value.toDouble();
        if(d > 0)
            return Qt::blue; //QVariant::fromValue(QColor(Qt::blue));
    }
    return QSqlTableModel::data(index, role); // forward everthing else to the base class
}


Edit: Changed line 3 above. Haven't used Qt in a while. The old code does work.
Last edited on
Topic archived. No new replies allowed.