我想添加一个QGraphicsTextItem,我想改变背景的颜色。我的意思是我希望包含文本的boundingRect具有特定的颜色。一种方法是创建一个QGraphicsRectItem并将其放在文本的背面,但我想知道是否有另一种方法可以做到这一点?
感谢您的帮助!
答案 0 :(得分:9)
我会继承QGraphicsTextItem
,例如:
class QGraphicsTextItemWithBackgroundColorOfMyChoosing : public QGraphicsTextItem
{
public:
QGraphicsTextItemWithBackgroundColorOfMyChoosing(const QString &text) :
QGraphicsTextItem(text) { }
void paint( QPainter *painter, const QStyleOptionGraphicsItem *o, QWidget *w) {
painter->setBrush(Qt::red);
painter->drawRect(boundingRect());
QGraphicsTextItem::paint(painter, o, w);
}
};
答案 1 :(得分:3)
您可以使用setHtml()将HTML写入QGraphicsTextItem,因此您可以使用例如填充背景。
item->setHtml("<div style='background-color:#666666;'>" + yourText + "</div>");
答案 2 :(得分:1)
这可能太少,太晚了,但以下对我有用,无需分类或重新实现。
item->setHtml(QString("<div style='background:rgba(255, 255, 255, 100%);'>" + QString("put your text here") + QString("</div>") );