Lukasz Czerwinski
Lukasz Czerwinski

Reputation: 15432

How to set background for QGraphicsSimpleTextItem (Qt C++)?

I have added to my QGraphicsScene a QGraphicsSimpleTextItem, but just a simple text is unreadable of current background. Therefore I'd like to set background color of the QGraphicsSimpleTextItem, but... there is no such method. What's the simplest solution?

Upvotes: 1

Views: 2860

Answers (3)

Lukasz Czerwinski
Lukasz Czerwinski

Reputation: 15432

It seems that the simplest solution is to use QGraphicsTextItem instead of QGraphicsSimpleTextIem and to call setHtml() in the constructor, for example:

this->setHtml(QString("<div style='background-color: #ffff00;'>") + text + "</div>");

Upvotes: 5

Chris
Chris

Reputation: 17535

To change the background of your whole scene:

myScene->setBackgroundBrush( Qt::red );

Or if you want to change the background of just your text item, you'll probably have to subclass QGraphicsSimpleTextItem and override the paint() method.

class MyTextItem : public QGraphicsSimpleTextIem {
    public:
        void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget=0 )
        {
            painter->setBrush( Qt::red );
            painter->drawRect( boundingRect() );
            QGraphicsSimpleTextItem::paint( painter, option, widget );
        }

Upvotes: 4

Matthew
Matthew

Reputation: 2829

Here is how you can access the background color.

QPalette currentPalette = myGraphicScene.palette();

// Set a new color for the background, use QPalette::Window
// as QPalette::Background is obsolete.
currentPalette.setColor( QPalette::Window, Qt::red );

// Set the palette.
myGraphicScene.setPalette( currentPalette );

Upvotes: -1

Related Questions