Вопрос

Is there a way to add a background color to a QGraphicsTextItem object?

I've created a QGraphicsScene, and need to display text inside it. I've created a QGraphicsTextItem to do the job. However, it's not very clear against the background, so I'm looking to highlight it, or set a background color to make it more visible. I haven't found anything in the documentation that does this though.

I'd like to avoid doing this the long way around if there's a better option available. Thanks for your answers!

Это было полезно?

Решение

You have a few options.

The easiest would be, setting an HTML with the desired style:

htmlItem = QtGui.QGraphicsTextItem()
htmlItem.setHtml('<div style="background:#ff8800;">html item</p>')

An alternative approach is subclassing the QGraphicsTextItem and doing the custom background with paint method.

class MyTextItem(QtGui.QGraphicsTextItem):
    def __init__(self, text, background, parent=None):
        super(MyTextItem, self).__init__(parent)
        self.setPlainText(text)
        self.background = background

    def paint(self, painter, option, widget):
        # paint the background
        painter.fillRect(option.rect, QtGui.QColor(self.background))

        # paint the normal TextItem with the default 'paint' method
        super(MyTextItem, self).paint(painter, option, widget)

Here is a basic example demonstrating the both:

import sys
from PySide import QtGui, QtCore

class MyTextItem(QtGui.QGraphicsTextItem):
    def __init__(self, text, background, parent=None):
        super(MyTextItem, self).__init__(parent)
        self.setPlainText(text)
        self.background = background

    def paint(self, painter, option, widget):
        # paint the background
        painter.fillRect(option.rect, QtGui.QColor(self.background))

        # paint the normal TextItem with the default 'paint' method
        super(MyTextItem, self).paint(painter, option, widget)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = QtGui.QGraphicsView()
    s = QtGui.QGraphicsScene()

    htmlItem = QtGui.QGraphicsTextItem()
    htmlItem.setHtml('<div style="background:#ff8800;">html item</p>')

    myItem = MyTextItem('my item', '#0088ff')

    s.addItem(htmlItem)
    myItem.setPos(0, 30)
    s.addItem(myItem)
    w.setScene(s)
    w.show()

    sys.exit(app.exec_())

Другие советы

Try This:

item = QtGui.QGraphicsTextItem()
item.setFormatTextColor("#value")
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top