【发布时间】:2016-04-18 23:04:03
【问题描述】:
我想添加一个 QGraphicsTextItem 并且我想改变背景的颜色。我的意思是我希望包含文本的 boundingRect 具有特定的颜色。一种方法是创建一个 QGraphicsRectItem 并将其放在文本的背面,但我想知道是否还有其他方法可以做到这一点?
感谢您的帮助!
【问题讨论】:
我想添加一个 QGraphicsTextItem 并且我想改变背景的颜色。我的意思是我希望包含文本的 boundingRect 具有特定的颜色。一种方法是创建一个 QGraphicsRectItem 并将其放在文本的背面,但我想知道是否还有其他方法可以做到这一点?
感谢您的帮助!
【问题讨论】:
我会继承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);
}
};
【讨论】:
您可以使用setHtml() 将 HTML 写入 QGraphicsTextItem,因此您可以使用例如填充背景
item->setHtml("<div style='background-color:#666666;'>" + yourText + "</div>");
【讨论】:
这可能太少,太晚了,但以下对我有用,无需子类或重新实现某些东西。
item->setHtml(QString("<div style='background:rgba(255, 255, 255, 100%);'>" + QString("put your text here") + QString("</div>") );
【讨论】:
QString,Romha 提出的解决方案对我不起作用。我今天不能说它是什么版本的 Qt(可能是 5.4 左右)。它在 Debian 7 下。(附注:我仍然赞成 Romha 的回答!)。随意标记删除或其他任何内容。我认为它可能会帮助处于类似困境中的其他人(显然它确实做到了,正如我在这里看到的两个赞成票。)