How to color or make text bold for particular cell in QTableView?

Vijay13 picture Vijay13 · Jan 21, 2014 · Viewed 14.6k times · Source

I have used QTableView to saw tabular data in my Qt program and somehow I need to differentiate some cells from others, can be done making font bold in those particular cells or painting background of those particular cells.

Can someone please provide code rather than just saying use QAbstractItemDelegate ?

I read through documentation of QAbstractItemDelegate but could not understand so please explain using example.

Answer

vahancho picture vahancho · Jan 22, 2014

In order to make text appear differently in your table view, you can modify your model, if any exists, and handle Qt::FontRole and/or Qt::ForegroundRole roles in the model's QAbstractItemModel::data() function. For example:

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::FontRole && index.column() == 0) { // First column items are bold.
        QFont font;
        font.setBold(true);
        return font;
    } else if (role == Qt::ForegroundRole && index.column() == 0) {
        return QColor(Qt::red);
    } else {
        [..]
    }

}