PDA

View Full Version : how to color a cell in a QTableView


JeanC
12th January 2008, 10:42
Hello,
I'm gonna try my luck here. On the other forum there are about 20 people asking for this with not much of results.

How can I color a cell in a QTableView?
For instance if the cell holds a '1' I want it blue, else leave it white.

I know I have to override QPaintEvent, but how? I have a pointer to the QTableView that was created in Designer, it's called 'table'.

Now what to do?

In the 'old days' you wrote yourself a paint() function and overwrote the original like table->paint(args) = somefunc. I understand it is not as straightforward in qt.

But please where are working examples for this, I'm getting weary wading through classes and members without much of examples trying to guess things together.
Jean

marcel
12th January 2008, 10:49
You have to subclass QItemDelegate and override its paint method.
In paint you have access to the model index of the cell being painted.

You will have to pass an instance of your delegate when you create the view.

JeanC
13th January 2008, 12:34
Got it working thanks
For those interested my code:

in the .h file add:


class Delegate : public QItemDelegate
{
Q_OBJECT
public:
Delegate(QWidget *parent = 0) : QItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};


in the .cpp, in a constructor


table->setItemDelegate(new Delegate);


and the event:


//---------------------------------------------------
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QString val;
if (qVariantCanConvert<QString>(index.data()))
val = qVariantValue<QString>(index.data());
if (val == "1")
{
painter->fillRect(option.rect, option.palette.highlight());
}
else
QItemDelegate::paint(painter, option, index);
}

aamer4yu
15th January 2008, 08:53
I was wondering if QTableWidgetItem::setBackground could be of some use in this case ??

one can get the tablewidgetitem(the cell) and set the bacground to it. :confused: