Question

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.

Was it helpful?

Solution 2

No need to go with abstract delegate. Styled delegate does most of the work you need. Use it and reimplement only needed behaviour.

.h:

#include <QStyledItemDelegate>

class MyDelegate : public QStyledItemDelegate
{
    Q_OBJECT

    public:
        explicit MyDelegate(QObject *parent = 0);

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

    private:
        bool shouldBeBold(const QModelIndex &index);
}

.cpp:

MyDelegate::MyDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}


void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);

    QVariant data = index.data(...); // pick the data you need here
    opt.font.setBold(shouldBeBold(data));

    QStyledItemDelegate::paint(painter, opt, index);
}

bool MyDelegate::shouldBeBold(const QModelIndex &index)
{
    // you need to implement this
}

Then apply delegate to the view. If shouldBeBold() returns false, delegate will paint like a standard one. If it returns true, it will apply bold font.

I hope that's enought for you to get started.

OTHER TIPS

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 {
        [..]
    }

}

If you don't have a model or a delegate and you don't want to create one, you can set the font of the cell directly:

QFont font(cell->font());
font.setBold(true);
cell->setFont(font);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top