有沒有辦法給添加背景顏色到QGraphicsTextItem
對象?PySide:將背景顏色添加到QGraphicsTextItem對象
我創建了一個QGraphicsScene
,並且需要在其中顯示文本。我創建了一個QGraphicsTextItem
來完成這項工作。但是,背景並不十分清晰,所以我正在尋找突出顯示,或者設置背景顏色以使其更清晰可見。我還沒有找到任何文件,但是這樣做。
如果有更好的選擇,我想避免這樣做。謝謝你的回答!
有沒有辦法給添加背景顏色到QGraphicsTextItem
對象?PySide:將背景顏色添加到QGraphicsTextItem對象
我創建了一個QGraphicsScene
,並且需要在其中顯示文本。我創建了一個QGraphicsTextItem
來完成這項工作。但是,背景並不十分清晰,所以我正在尋找突出顯示,或者設置背景顏色以使其更清晰可見。我還沒有找到任何文件,但是這樣做。
如果有更好的選擇,我想避免這樣做。謝謝你的回答!
您有幾種選擇。
最簡單的是,設置一個HTML與期望的樣式:
htmlItem = QtGui.QGraphicsTextItem()
htmlItem.setHtml('<div style="background:#ff8800;">html item</p>')
的另一種方法是子類QGraphicsTextItem
並用paint
方法做自定義的背景。
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)
下面是一個簡單的例子展示了兩種:
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_())
試試這個:
item = QtGui.QGraphicsTextItem()
item.setFormatTextColor("#value")
它給了我這個錯誤:'AttributeError:'PySide.QtGui.QGraphicsTextItem'對象沒有屬性'setFormatTextColor'' – sorbet
對不起,將 item.setformatTextColor改爲item.setDefaultTextColor – user1976336
什麼是「漫長的道路」你要設法避免? – Avaris
我的'長途'是創建一個'QGraphicsRectItem',用一種顏色填充它,然後讓它跟隨我的'QGraphicsTextItem'到處走。它會起作用,但如果可用的話,我想使用更好的方法。 – sorbet