我在画布上有一些小的图片,需要显示一些文字。当出现断线时,垂直行距不必要地大,这使得文本被绘制在图形项之外。我一直在寻找一种在QGraphicsTextItem上设置行距(或者可能是高度)的方法,但是没有运气。
我试过了;
setHtml("<div line-height=100%>some text</div>") 等。
需要设置行间空间的代码是:
class GraphicText(QtGui.QGraphicsTextItem):
def __init__(self, text='', font=None, editable=False, text_width = None, **kw):
super(GraphicText, self).__init__(**kw)
if editable:
self.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
else:
self.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
if font:
self.setFont(font)
self.setText(text, text_width)
def setText(self, text = '', text_width = None):
cw = self.textWidth()
try:
width = text_width or (cw if cw>0 else False) or self.parentItem().boundingRect().width()-4
except AttributeError:
width = 100
self.setTextWidth(width)
self.setHtml(text)
rect = self.boundingRect()
self.setPos(-rect.width() / 2, -rect.height() / 2) # center这是Python/PySide,但否则API与C++几乎相同。HTML当前作为参数'text‘传递给init方法。QGraphicsTextItem的父级是QGraphicsItem。
请帮帮忙,这真是眼中钉。
干杯,拉斯。
发布于 2013-10-30 20:11:06
当项目的html代码中的<br>导致行中断时,不会再现此行为。自动断线使用"test1 test2"内容和setTextWidth也很好。但是,当行中断是由<p></p>标记引起时,就会出现不必要的大行高。我想这是你的案子。它可以很容易地固定:
item->document()->setDefaultStyleSheet("p { margin: 0; }");请注意,您需要在设置项的内容之前调用它。此命令不影响当前内容。
https://stackoverflow.com/questions/19464773
复制相似问题