PDA

View Full Version : Changing the background color of a QGraphicsSimpleTextItem



psychocowtipper
5th May 2011, 22:32
Hi, I have a class that inherits from the QGraphicsSimpleTextItem class. I cannot figure out how to make the background change when this happens. Right now, I figured out that by changing the pen I can make the text outlines change:


text_item->setPen(QPen(QColor(Qt::black)));

Running this code will change the outlines of the text in text_item, but I want a more dramatic change. I am looking for a way to replace that line with something that will change the background of my text_item when I choose. I tried overwriting the paint() function inherited from QGraphicsItem like so:


void MyTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QBrush brush(Qt::white);
painter->setBrush(brush);
painter->drawRect(0,0,50,50);
this->setPen(QPen(Qt::black));
}

The first three lines of the function paint a white rectangle as the background (which is what I am aiming for), but setting the pen does nothing to display the text. So, I can either have the text with no change in background, or when I try to change the background the text doesn't show up. The fourth line in that function seems to do nothing. Is there any way I can have this class still display the text but also be able to change the background?

Thanks in advance,
psychocowtipper

Lykurg
5th May 2011, 22:41
subclass the paint method as you have done and inside just draw the background as you like. Afterwards just call the paint method of the base class, the simple text item in your case and all should work as you want it to.

And may be you need to change the pen outside the paint method, but I am not sure about it.

psychocowtipper
6th May 2011, 19:50
Thank you so much! I was able to get it working just by changing my overloaded paint() function to:

void MyTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{

QBrush brush(Qt::white);
painter->setBrush(brush);
painter->drawRect(0,0,70,35);

QGraphicsSimpleTextItem::paint(painter,option,widg et);

}