如何设置QGraphicsSimpleTextItem(QtC++)的背景

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

本文关键字:背景 QtC++ QGraphicsSimpleTextItem 设置 何设置      更新时间:2023-10-16

我在QGraphicsScene中添加了一个QGraphicsSimpleTextItem,但只有一个简单的文本无法读取当前背景。所以我想设置QGraphicsSimpleTextItem的背景色,但是。。。没有这样的方法。最简单的解决方案是什么?

似乎最简单的解决方案是使用QGraphicsTextItem而不是QGraphicsSimpleTextIem,并在构造函数中调用setHtml(),例如:

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

要更改整个场景的背景:

myScene->setBackgroundBrush( Qt::red );

或者,如果您只想更改文本项的背景,您可能需要将QGraphicsSimpleTextItem子类化并覆盖paint()方法。

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 );
        }

以下是如何访问背景颜色。

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 );