Lars
Lars

Reputation: 1969

qt set line spacing.height in QGraphicsTextItem

I have some small graphicsitems on a canvas which need to display some text. When there is a line break, the vertical line spacing is unnecessarily large, which makes the text be drawn outside the graphic items. I have been searching for a way to set the line spacing (or maybe height) on a QGraphicsTextItem but no luck.

I have tried;

setHtml("<div line-height=100%>some text</div>") 

etc.

The code where a need to set the inter line apace is:

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

This is Python/PySide, but otherwise the API is pretty much the same as for C++. The HTML is currently passed into the init method as parameter 'text'. The parent of the QGraphicsTextItem is a QGraphicsItem.

Please help, this is really an eyesore.

Cheers, Lars.

Upvotes: 1

Views: 1780

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

This behavior is not reproduced when the line break is caused by <br> in the item's html code. Auto line break using "test1 test2" content and setTextWidth is also working fine. But when the line break is caused by <p></p> tags, the unnecessarily large line height shows up. I assume that this is your case. It can be easily fixed:

item->document()->setDefaultStyleSheet("p { margin: 0; }");

Note that you need to call it before setting item's content. This command doesn't affect current content.

Upvotes: 2

Related Questions